If we have multiple executors configured as beans; we can resolve conflict between them by using a qualifier with @Async#value
package com.logicbig.example; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; @Component public class MyBean { @Async("myExecutor1") public void runTask() { System.out.printf("Running task thread: %s%n", Thread.currentThread().getName()); } }
package com.logicbig.example; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.core.task.TaskExecutor; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ConcurrentTaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @EnableAsync @ComponentScan public class AsyncExample { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AsyncExample.class); MyBean bean = context.getBean(MyBean.class); System.out.printf("calling async method from thread: %s%n", Thread.currentThread().getName()); bean.runTask(); System.out.printf("After calling async method from thread: %s%n", Thread.currentThread().getName()); //shutting down executor ConcurrentTaskExecutor taskExecutor = context.getBean(ConcurrentTaskExecutor.class); ExecutorService es = (ExecutorService) taskExecutor.getConcurrentExecutor(); es.shutdown(); } @Bean @Qualifier("myExecutor1") public TaskExecutor taskExecutor2 () { return new ConcurrentTaskExecutor( Executors.newFixedThreadPool(3)); } @Bean @Qualifier("myExecutor2") public TaskExecutor taskExecutor () { return new ThreadPoolTaskExecutor(); } }
calling async method from thread: com.logicbig.example.AsyncExample.main()After calling async method from thread: com.logicbig.example.AsyncExample.main()Running task thread: pool-1-thread-1
Dependencies and Technologies Used:
Version compatibilities of spring-context with this example:
Versions in green have been tested.