Backend Development 12 min read

Using @Async in Spring Boot: Configuration, Best Practices, and Common Pitfalls

This article explains how to enable and configure Spring Boot's @Async annotation, provides code examples for thread‑pool setup and asynchronous service methods, and discusses important caveats such as calling async methods from the same class, transaction incompatibility, blocking issues, and exception handling.

Top Architect
Top Architect
Top Architect
Using @Async in Spring Boot: Configuration, Best Practices, and Common Pitfalls

@Async is presented as a powerful yet simple way to improve performance in Spring Boot applications by running methods in the background while the main thread continues.

To use it, add @EnableAsync to a configuration class or the main application class:

@SpringBootApplication
@EnableAsync
public class BackendAsjApplication {
}

Define a ThreadPoolTaskExecutor bean to control pool size, queue capacity, and thread naming, optionally adding a rejection handler:

@Bean
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("MyAsyncThread-");
executor.setRejectedExecutionHandler((r, executor1) -> log.warn("Task rejected, thread pool is full and queue is also full"));
executor.initialize();
return executor;
}

Apply @Async to service methods, for example:

@Service
public class EmailService {
@Async
public void sendEmail() {
// asynchronous code
}
}

Common pitfalls:

Do not call an @Async method from the same class; it will execute synchronously. Use a separate bean instead.

Methods annotated with @Transactional lose transaction context when executed asynchronously, which can lead to data inconsistency.

Long‑running tasks can block the default pool; consider defining a dedicated executor for heavy tasks:

@Primary
@Bean(name = "taskExecutorDefault")
public ThreadPoolTaskExecutor taskExecutorDefault() {
// same configuration as above
}
@Bean(name = "taskExecutorForHeavyTasks")
public ThreadPoolTaskExecutor taskExecutorForHeavyTasks() {
// same configuration, different thread name prefix
}

Specify the executor when declaring the async method:

@Service
public class EmailService {
@Async("taskExecutorForHeavyTasks")
public void sendEmailHeavy() {
// heavy task implementation
}
}

Exception handling: async methods do not propagate exceptions to the caller. Wrap the result in a Future and handle errors explicitly:

@Service
public class EmailService {
@Async
public Future
sendEmail() throws Exception {
throw new Exception("Oops, cannot send email!");
}
}
@Service
public class PurchaseService {
@Autowired
private EmailService emailService;
public void purchase() {
try {
Future
future = emailService.sendEmail();
String result = future.get();
System.out.println("Result: " + result);
} catch (Exception e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
}

In summary, @Async can greatly improve scalability when used correctly, but developers must be aware of its limitations regarding self‑invocation, transaction boundaries, thread blocking, and exception propagation.

BackendJavaasynchronousSpring BootAsyncThreadPoolTaskExecutor
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.