Spring @Async limit number of threads

Martin V. picture Martin V. · Nov 3, 2012 · Viewed 43.9k times · Source

My question is very similar to this one : @Async prevent a thread to continue until other thread have finished

Basically i need run ~ hundreds of computations in more threads. I want to run only some amount of parallel threads e.g. 5 threads with 5 computationis in paralell.

I am using spring framework and @Async option is natural choice. I do not need full-featured JMS queue, that`s a bit overhead for me.

Any ideas ? Thank you

Answer

Siggen picture Siggen · May 7, 2014

If you are using Spring's Java-configuration, your config class needs to implements AsyncConfigurer:

@Configuration
@EnableAsync
public class AppConfig implements AsyncConfigurer {

    [...]

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(5);
        executor.setQueueCapacity(50);
        executor.setThreadNamePrefix("MyExecutor-");
        executor.initialize();
        return executor;
    }
}

See @EnableAsync documentation for more details : http://docs.spring.io/spring/docs/3.1.x/javadoc-api/org/springframework/scheduling/annotation/EnableAsync.html