Skip to content

wait for any finished callable return value as soon as it finished in list of callables

TL;DR: I want to be able to wait for all Futures, but get the return value of each callable as soon as it finish.

Assuming I have multiple callables running using an executor. if I have a list of Futures, is there any elegant way of getting the retured value of any finished task, and than keep waiting for the rest of the task in the same way?


That’s what ExecutorCompletionService is for.

Executor executor = ...;
List<Callable<T>> tasks = List.of(...);
CompletionService<T> completionService = new ExecutorCompletionService<>(executor);
for (int i = 0; i < tasks.size(); i++) {
    T result = completionService.take().get();
    // A task has completed. Use its result.