greyfox greyfox - 1 year ago 126
Java Question

Multiple ThreadPoolTaskExecuters Spring Java Config

I have a need for multiple tasks executors in my application but I am not seeing how do so with Java Config. The XML version is straight forward but I must be missing something with the Java Config

I need two different executors with different queue and thread pool sizes, how can this be done using Java Config?

Here is my AsyncConfig class

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

public class AsyncConfig implements AsyncConfigurer {

Environment environment;

public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(environment.getRequiredProperty("aysnc.executor.poolSize", Integer.class));
executor.setMaxPoolSize(environment.getRequiredProperty("aysnc.executor.maxPoolSize", Integer.class));
executor.setQueueCapacity(environment.getRequiredProperty("aysnc.executor.queueCapacity", Integer.class));
return executor;

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

Answer Source

I think you can remove the interface, define your 2 Executors in your JavaConfig marked as @Bean(name = "nameOfExecutor") and then use the bean name in @Async("nameOfExecutor") as per the docs: May be used to determine the target executor to be used when executing this method, matching the qualifier value (or the bean name) of a specific Executor or TaskExecutor bean definition.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download