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?
Advertisement
Answer
That’s what ExecutorCompletionService
is for.
Executor executor = ...; List<Callable<T>> tasks = List.of(...); CompletionService<T> completionService = new ExecutorCompletionService<>(executor); tasks.forEach(completionService::submit); for (int i = 0; i < tasks.size(); i++) { T result = completionService.take().get(); // A task has completed. Use its result. }