Just wanted to check in to see if anyone had a faster way to set the TaskExecutor for Spring MVC within spring boot (using auto configuration). This is what I have so far:
@Bean
protected ThreadPoolTaskExecutor mvcTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setThreadNamePrefix("my-mvc-task-executor-");
executor.setCorePoolSize(5);
executor.setMaxPoolSize(200);
return executor;
}
@Bean
protected WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
configurer.setTaskExecutor(mvcTaskExecutor());
}
};
}
Does anyone have a better/faster way to do this?
-Joshua
The TaskExecutor was originally created to give other Spring components an abstraction for thread pooling where needed. Components such as the ApplicationEventMulticaster , JMS's AbstractMessageListenerContainer , and Quartz integration all use the TaskExecutor abstraction to pool threads.
Interface TaskExecutorSimple task executor interface that abstracts the execution of a Runnable . Implementations can use all sorts of different execution strategies, such as: synchronous, asynchronous, using a thread pool, and more.
Spring also features implementations of those interfaces that support thread pools or delegation to CommonJ within an application server environment.
One way to achieve this is to use Spring's ConcurrentTaskExceptor class. This class acts as adapter between Spring's TaskExecutor and JDK's Executor.
@Bean
protected WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
configurer.setTaskExecutor(new ConcurrentTaskExecutor(Executors.newFixedThreadPool(5)));
}
};
}
One problem with above is that you can't specify maximum pool size. But you can always create a new factory method, createThreadPool(int core, int max)
to get you configurable thread pools.
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