Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a non-blocking method analogous to ExecutorService invokeAll?

Java's ExecutorService interface defines a method called invokeAll which takes in a Collection of Callable objects to be processed concurrently. However, the invokeAll method itself waits for all of the tasks to finish running before returning, making it a blocking method.

In my test environment I don't care about the return values of these tasks, I just need them to run concurrently. Now, I know I can manually create new Thread or Runnable objects and start them up myself, but it would be nice and clean if I could simply create a Collection of Runnable or Callable objects and pass them off to a method that starts executing them for me and immediately returns.

Does anybody know of an existing library Class that has the method I am describing? I could not find one while doing some research.

like image 657
Default Avatar asked Aug 28 '13 16:08

Default


People also ask

Is ExecutorService submit blocking?

Right, this ExecutorService blocks tasks on submission without blocking caller thread. Job just getting submitted and will be processed asynchronously when there will be enough system resources for it.

Is invokeAll a blocking call?

It looks as invokeAll is blocking.

How do I stop the ExecutorService thread?

To properly shut down an ExecutorService, we have the shutdown() and shutdownNow() APIs. The shutdown() method doesn't cause immediate destruction of the ExecutorService. It will make the ExecutorService stop accepting new tasks and shut down after all running threads finish their current work: executorService.

Which method can cancel the future task triggered by submit () of ExecutorService?

You can cancel the task submitted to ExecutorService by simply calling the cancel method on the future submitted when the task is submitted.


Video Answer


1 Answers

I'm actually surprised invokeAll behaves like this. The submit method doesn't block, so it's just a matter of calling that for each task:

public static <T> Collection<Future<T>> submitAll(ExecutorService service, Collection<? extends Callable<T>> tasks) {
    Collection<Future<T>> futures = new ArrayList<>(tasks.size());
    for (Callable<T> task: tasks) {
        futures.add(service.submit(task));
    }
    return futures;
}
like image 130
bdkosher Avatar answered Oct 19 '22 23:10

bdkosher