andPat andPat - 7 months ago 61
Java Question

Parallel for with Spring Asynchronous execution

I want to iterate over a list of elements and execute operations on them asynchronously (in a parallel way).

Here is my code:

ElemManager elemManager;

List<Elem> elems = new ArrayList<>();

for ( Elem elem : elems ) {

where ElemManager is:

public class ElemManager {

public Future<String> doSomething( Elem elem ) {
// do something
return "done";

I have also created a thread pool in spring context and enabled asynchronous execution so:

public class TaskConfiguration implements AsyncConfigurer {

public Executor getAsyncExecutor() {
final ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setMaxPoolSize( 5 );
threadPoolTaskExecutor.setAwaitTerminationSeconds( 60 );
return threadPoolTaskExecutor;

public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new CustomAsyncExceptionHandler();


Am I missing something? Is it the correct way to parallel execute a method through Spring Asynchronous execution support?


You're not actually invoking that using Spring. You're just invoking it like a plain old method.

But aside from this, calling Future.get() means that you wait for the future to complete.

Add the Futures to a list first, and then call .get() on them in turn:

List<Future<?>> futures = new ArrayList<>();
for ( Elem elem : elems ) {
for (Future<?> future : futures) {