Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExecutorService.invokeAll does NOT support collection of runnable task

Wanted to run collection of Runnable task through invokeAll(..) method of ExecutorService. But that's not supported as of now (supports collection of Callable task only)

Any specific reason for this? What's the alternative to do something similar.

like image 436
rai.skumar Avatar asked Jun 06 '14 12:06

rai.skumar


People also ask

Is ExecutorService invokeAll blocking?

invokeAll() does indeed run the callable tasks in it's own thread, but it also blocks waiting for the tasks to complete. submit() does not block.

What are the advantages of using ExecutorService instead of creating threads directly?

Below are some benefits: Executor service manage thread in asynchronous way. Use Future callable to get the return result after thread completion. Manage allocation of work to free thread and resale completed work from thread for assigning new work automatically.

What is ExecutorService and how its works?

The ExecutorService interface extends Executor by adding methods that help manage and control the execution of threads. It is defined in java. util. concurrent package. It defines methods that execute the threads that return results, a set of threads that determine the shutdown status.


2 Answers

Runnable task = new Runnable() { 
     public void run() {

     }
};

Callable<Object> c = Executors.callable(task);

Just found that, Executors provides utility method to convert Runnable task into a Callable task. That explains why we don't have overloaded invokeAll which takes Runnable task as well.

like image 106
rai.skumar Avatar answered Oct 18 '22 01:10

rai.skumar


Simply transform the runnables into callables:

List<Callable<Void>> callables = new ArrayList<>();
for (Runnable r : runnables) {
    callables.add(toCallable(r));
}
executor.invokeAll(callables);

private Callable<Void> toCallable(final Runnable runnable) {
    return new Callable<Void>() {
        @Override
        public Void call() {
            runnable.run();
            return null;
        }
    };
}
like image 30
JB Nizet Avatar answered Oct 17 '22 23:10

JB Nizet