Skip to main content
InterviewHubPRO
Section Overview
Q10

Question 10 of 50

Part 1: Spring Core, Auto-Configuration & Architecture (1 - 10)

20%
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:

  1. Must enable with @EnableAsync.
  2. Must configure a custom ThreadPoolTaskExecutor (avoid default SimpleAsyncTaskExecutor which creates a new unbounded thread per task).
  3. The method must be public and 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;
    }
}