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

joshuawhite929
  • 2,635
  • 2
  • 16
  • 16
  • 2
    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`. – Thilo Mar 02 '15 at 00:09
  • 1
    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. – joshuawhite929 Mar 02 '15 at 00:12
  • 1
    thanks! your question was actually a good answer for me :) – harshadura Dec 27 '15 at 09:08

1 Answers1

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.

Mohit
  • 1,740
  • 1
  • 15
  • 19