Question

Here's what I want to achieve: I want to have some object (probably an executor of some sort) to which I can submit a "batch" of tasks to be executed (say List<Callable<T>>). When all of these tasks have finished running I want to be notified (probably through a value available in a Future object).

This "executor" should be able to handle several batches at once. In other words: two (or more) code sites can submit two different batches and each of these sites will be notified only when "his" batch is over.

Even better, I want that Future to provide me with a List<T> holding the values that were returned by the various tasks (Callables).

Summarizing the above I am looking for something that offers an API that is conceptually identical to:

public T Future<List<T>> submitBatch(List<Callable<T>> tasks)

What canned constructs from java.util.concurrent can help me the most in achieving that?

Was it helpful?

Solution

An ExecutorService has just the method for that.

And it (nearly) fits your demands, since it returns a List<Future<T>>.

Therefore:

final List<Future<Whatever>> list = service.invokeAll(myCallables);
// walk list and call .get() on each future

Note that as the doc says, this method will wait until all callables are done. Also, you still need to check for failures in each Future.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top