Java Executor InvokeAll with Timeout

Run a batch on a fixed thread pool with invokeAll and a deadline, inspect completed futures, and shut the executor down cleanly.

JavaResilience

Code

snippet
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class BatchRunner {

    public static void main(String[] args) throws InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(3);
        List<Callable<String>> tasks = new ArrayList<>();
        for (int id = 1; id <= 5; id++) {
            final int taskId = id;
            tasks.add(() -> {
                Thread.sleep(taskId * 150L);
                return "task-" + taskId;
            });
        }

        try {
            List<Future<String>> futures = pool.invokeAll(tasks, 500, TimeUnit.MILLISECONDS);
            int succeeded = 0;
            int cancelled = 0;

            for (int index = 0; index < futures.size(); index++) {
                Future<String> future = futures.get(index);
                if (future.isCancelled()) {
                    cancelled++;
                    System.out.println("task " + (index + 1) + " cancelled");
                    continue;
                }
                try {
                    System.out.println("result: " + future.get());
                    succeeded++;
                } catch (ExecutionException error) {
                    System.out.println("task " + (index + 1) + " failed: " + error.getCause());
                }
            }
            System.out.println("succeeded=" + succeeded + " cancelled=" + cancelled);
        } finally {
            pool.shutdownNow();
            if (!pool.awaitTermination(2, TimeUnit.SECONDS)) {
                System.err.println("pool did not terminate in time");
            }
        }
    }
}