简体   繁体   中英

how can executorService store result of task `i` in `array[i]`?

I read this post about executorService

I want to fill a fixed size collection of results when order matters.

I could fill an array, when I know task i should store its result in array[i] .

Is there another built-in way to store results in the order the tasks were submitted? And can I fill a list instead of an array?

Simply store the Future s returned by submit() in an array or list, and then iterate over this list and call get() on each future:

List<Callable<Result>> tasks = ...;
List<Future<Result>> futures = new ArrayList<>();
for (Callable<Result> task : tasks) {
    futures.add(executor.submit(task));
}

List<Result> results = new ArrayList<>();
for (Future<Result> future : futures) {
    results.add(future.get());
}

You could use Executors.invokeAll() method. From the javadocs:

Parameters:

tasks - the collection of tasks

Returns:

A list of Futures representing the tasks, in the same sequential order as produced by the iterator for the given task list, each of which has completed.

ExecutorService executor = Executors.newFixedThreadPool(SOME_SIZE);

Collection<Callable<T>> tasks = ...; // fill collection with callable tasks

List<Future<T>> futures = executor.invokeAll(tasks);

invokeAll() returns when all submitted tasks have finished their execution.

Then iterate over the returned futures and invoke get() on each one of them:

List<T> results = 
    futures.stream().map(Future::get).collect(Collectors.toList());

Order of results will match that one of tasks collection.

In a one-liner:

List<T> results = 
    executor.invokeAll(tasks).stream().map(Future::get).collect(Collectors.toList());

Add the results from Future objects to a list in the same order as they were created:

// given some tasks and an executor 
List<Callable<MyResult>> tasks;
ExecutorService exec;

List<MyResult> results = exec.invokeAll(tasks).stream()
  .map(Future::get).collect(Collectors.toList());

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