Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot - Any shortcuts for setting TaskExecutor?

Tags:

spring-boot

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

like image 837
joshuawhite929 Avatar asked Mar 02 '15 00:03

joshuawhite929


People also ask

What is the use of TaskExecutor in spring?

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.

What is TaskExecutor?

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.

Does spring use thread pool?

Spring also features implementations of those interfaces that support thread pools or delegation to CommonJ within an application server environment.


Video Answer


1 Answers

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.

like image 69
Mohit Avatar answered Oct 21 '22 16:10

Mohit