Spring Boot Asynchronous Request Processing Task Executor Configuration

Viewed 2271

From this doc I have learned that, now we can return Callable<T> from any action method. And spring will execute this action in a separate thread with the help of a TaskExecutor. This blog only says that this TaskExecutor is configurable. But I did not find a way to configure this TaskExecutor in spring boot application. Can anyone help me?

My another question is should I worry about the configuration of this TaskExecutor like threadpool size, queue size etc?

As pkoli asked, here is my Main class

@SpringBootApplication
public class MyWebApiApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(MyWebApiApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(MyWebApiApplication.class);
    }

    @Bean
    public Executor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("MyThread-");
        executor.initialize();
        return executor;
    }
}
2 Answers

Finally found answer here

To use other implementation of TaskExecutor we can extend our configuration class from WebMvcConfigurerAdapter or we can use it as bean. For example in a boot application:

@SpringBootApplication
public class AsyncConfigExample{
    @Bean
    WebMvcConfigurer configurer(){
        return new WebMvcConfigurerAdapter(){
            @Override
            public void configureAsyncSupport (AsyncSupportConfigurer configurer) {
                ThreadPoolTaskExecutor t = new ThreadPoolTaskExecutor();
                t.setCorePoolSize(10);
                t.setMaxPoolSize(100);
                t.setQueueCapacity(50);
                t.setAllowCoreThreadTimeOut(true);
                t.setKeepAliveSeconds(120);
                t.initialize();
                configurer.setTaskExecutor(t);
            }
        };
    }
    public static void main (String[] args) {
        SpringApplication.run(AsyncConfigExample.class, args);
    }
}
Related