java – How to create a different ThreadPoolTaskExecutor in Spring Boot?

java – How to create a different ThreadPoolTaskExecutor in Spring Boot?

First of all, you can define your thread pool executor and use them as a configure them as beans like this –

@Configuration
public class ThreadConfig {
    @Bean
    public TaskExecutor executorA() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(4);
        executor.setMaxPoolSize(4);
        executor.setThreadNamePrefix(default_task_executor_thread);
        executor.initialize();
        return executor;
    } 

    @Bean
    public TaskExecutor executorB() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(4);
        executor.setMaxPoolSize(4);
        executor.setThreadNamePrefix(executor-B);
        executor.initialize();
        return executor;
    }
}  

After that, you can specify your executor on method level like this –

@Async(executorA)
public void methodWithVoidReturnType(String s) {
    .....
}

@Async(executorA)
public Future<String> methodWithSomeReturnType() { 
   ...
   try {
      Thread.sleep(5000);
       return new AsyncResult<String>(hello world !!!!);
   } catch (InterruptedException e) {
      ...
   }

   return null;
}
@Bean(name = threadPoolExecutor)
public Executor getAsyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(7);
    executor.setMaxPoolSize(42);
    executor.setQueueCapacity(11);
    executor.setThreadNamePrefix(threadPoolExecutor-);
    executor.initialize();
    return executor;
}

@Bean(name = ConcurrentTaskExecutor)
public TaskExecutor taskExecutor2 () {
    return new ConcurrentTaskExecutor(
            Executors.newFixedThreadPool(3));
}

@Override
@Async(threadPoolExecutor)
public void createUserWithThreadPoolExecutor(){
    System.out.println(Currently Executing thread name -  + Thread.currentThread().getName());
    System.out.println(User created with thread pool executor);
}

@Override
@Async(ConcurrentTaskExecutor)
public void createUserWithConcurrentExecutor(){
    System.out.println(Currently Executing thread name -  + Thread.currentThread().getName());
    System.out.println(User created with concurrent task executor);
}

java – How to create a different ThreadPoolTaskExecutor in Spring Boot?

Leave a Reply

Your email address will not be published. Required fields are marked *