Spring Boot - Any shortcuts for setting TaskExecutor?
Asked Answered
T

1

14

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

Troxler answered 2/3, 2015 at 0:5 Comment(3)
By "better/faster" you mean with less lines of code? What you have now is not bad. If anything, you may want to make the two magic integers in there configurable by injecting them as @Value.Janitor
Yes, I am looking for less code (always). I agree with your point about the magic numbers though. I thought the extra code would be distracting.Troxler
thanks! your question was actually a good answer for me :)Sewoll
G
4

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.

Grimes answered 17/11, 2015 at 13:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.