To specify a custom Executor we just need to configure it as a bean. If don't provide a TaskExecutor as a bean. Spring will use a default executor implicitly as seen in the last example
Example
package com.logicbig.example;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
@Async
public void runTask() {
System.out.printf("Running task thread: %s%n",
Thread.currentThread().getName());
}
}
package com.logicbig.example;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ConcurrentTaskExecutor;
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
public TaskExecutor taskExecutor () {
return new ConcurrentTaskExecutor(
Executors.newFixedThreadPool(3));
}
}
Output
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
Example Project
Dependencies and Technologies Used:
spring-context 6.2.12 (Spring Context) Version Compatibility: 4.2.0.RELEASE - 6.2.12Version List
×
Version compatibilities of spring-context with this example: