toto
toto

Reputation: 1377

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?

Upvotes: 1

Views: 365

Answers (1)

user3453226
user3453226

Reputation:

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.
}

Upvotes: 1

Related Questions