Timeouts in Minitab

Timeouts are important for programs that connect to external resources or that otherwise need to bound execution time. Implementing timeouts in Java is straightforward using ExecutorService and Future.

import java.util.concurrent.*;

public class Timeouts {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newSingleThreadExecutor();

        // For our example, suppose we're executing an external
        // call that returns its result after 2s.
        Future<String> future1 = executor.submit(() -> {
            Thread.sleep(2000);
            return "result 1";
        });

        // Here's the implementation of a timeout.
        // We use Future.get() with a timeout parameter.
        // If the operation takes more than the allowed 1s,
        // it will throw a TimeoutException.
        try {
            String result = future1.get(1, TimeUnit.SECONDS);
            System.out.println(result);
        } catch (TimeoutException e) {
            System.out.println("timeout 1");
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        // If we allow a longer timeout of 3s, then the operation
        // will succeed and we'll print the result.
        Future<String> future2 = executor.submit(() -> {
            Thread.sleep(2000);
            return "result 2";
        });

        try {
            String result = future2.get(3, TimeUnit.SECONDS);
            System.out.println(result);
        } catch (TimeoutException e) {
            System.out.println("timeout 2");
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        executor.shutdown();
    }
}

Running this program shows the first operation timing out and the second succeeding.

$ javac Timeouts.java
$ java Timeouts
timeout 1
result 2

In this Java implementation, we use ExecutorService to submit tasks that return Future objects. The Future.get() method is used with a timeout parameter to implement the timeout functionality. If the operation doesn’t complete within the specified time, a TimeoutException is thrown.

This approach provides similar functionality to the original example, allowing us to bound the execution time of operations and handle timeouts gracefully.