Spring Boot & Microservices (50 Qs)•Part 1: Spring Core, Auto-Configuration & Architecture (1 - 10)
How do you implement asynchronous execution with `@Async` in Spring?
senior LevelCode ExampleAsync & PromisesSystem Design
In Simple Words:
Annotating a method with @Async runs it in a separate background thread from a dedicated thread pool:
- Must enable with
@EnableAsync. - Must configure a custom
ThreadPoolTaskExecutor(avoid defaultSimpleAsyncTaskExecutorwhich creates a new unbounded thread per task). - The method must be
publicand called from an external bean to pass through the AOP proxy.
java
@Configuration
@EnableAsync
public class AsyncConfig {
@Bean(name = "taskExecutor")
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(50);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("AsyncWorker-");
executor.initialize();
return executor;
}
}