简体   繁体   中英

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);
tasks.forEach(completionService::submit);
for (int i = 0; i < tasks.size(); i++) {
    T result = completionService.take().get();
    // A task has completed. Use its result.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM