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.
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.
It looks as invokeAll is blocking.
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.
You can cancel the task submitted to ExecutorService by simply calling the cancel method on the future submitted when the task is submitted.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With