Async Processing
@Async, TaskExecutor configuration, CompletableFuture returns, async error handling
- Offload long-running work to a thread pool with @Async
- Configure a custom ThreadPoolTaskExecutor
- Handle exceptions thrown by @Async methods
Course:
Spring Boot Series Instructor: Shreyansh Prerequisites: Spring Boot AOP, Spring Boot @Async Basics, Java Multithreading (Future, Callable, CompletableFuture)
Table of Contents
- Conditions for @Async to Work Properly
- How @Async Works Internally (AOP)
- @Async and @Transactional Together
- @Async Method Return Types
- Exception Handling in @Async Methods
- Key Observations
- Common Mistakes
- Best Practices
- Interview Notes
- Summary
Conditions for `@Async` to Work Properly
Overview
@Async does not always work just because you add the annotation. There are two mandatory conditions that must be satisfied, and violating either will cause the annotation to be silently ignored — no error is thrown, but the method runs on the same thread instead of a new one.
The Two Conditions
| # | Condition | Why |
|---|---|---|
| 1 | The @Async-annotated method must be in a different class from the caller | AOP interception only happens across class boundaries |
| 2 | The @Async-annotated method must be public | AOP proxy cannot intercept private or protected methods |
Why These Conditions Exist AOP Interception
@Async is implemented using Spring AOP. The mechanism works like this:
- Spring scans for
@Async-annotated methods at startup - Spring wraps the bean in a proxy object
- When a caller invokes the method through the proxy, the proxy intercepts the call and executes it on a new thread from the thread pool
- The proxy is bypassed when:
- The call is within the same class (
this.methodName()) - The method is private (proxies cannot override private methods)
Broken Example Same Class Invocation
1@RestController2public class UserController {3
4 // ❌ BROKEN: @Async method is in the SAME class as the caller5 @GetMapping("/get-user")6 public String getUser() {7 System.out.println("getUser thread: " + Thread.currentThread().getName());8 test(); // Calling async method in the same class9 return "Done";10 }11
12 @Async13 public void test() {14 // EXPECTATION: runs on a new thread15 // REALITY: runs on the SAME thread as getUser()16 System.out.println("test thread: " + Thread.currentThread().getName());17 }18}getUser thread: http-nio-8080-exec-1 test thread: http-nio-8080-exec-1 ← SAME thread! @Async did nothing.
Expected output (what you wanted):
1getUser thread: http-nio-8080-exec-12test thread: task-1 ← Different threadFixed Example Method in Separate Class
1// Caller class2@RestController3public class UserController {4
5 @Autowired6 private AsyncService asyncService; // Injected from a DIFFERENT class7
8 @GetMapping("/get-user")9 public String getUser() {10 System.out.println("getUser thread: " + Thread.currentThread().getName());11 asyncService.test(); // Calling async method from a DIFFERENT class ✅12 return "Done";13 }14}1// Async method in a separate class2@Component3public class AsyncService {4
5 @Async // ✅ public method6 public void test() {7 System.out.println("test thread: " + Thread.currentThread().getName());8 }9}getUser thread: http-nio-8080-exec-1 test thread: task-1 ← New thread created ✅
Internal Mechanism Diagram
How `@Async` Works Internally (AOP)
Step-by-Step
- Application Startup: Spring detects
@EnableAsyncand scans all beans for@Async-annotated methods - Proxy Creation: Spring wraps each bean containing
@Asyncmethods in a CGLIB or JDK dynamic proxy - Method Invocation: When the caller calls
asyncService.test(), it actually callsasyncServiceProxy.test() - Interception: The proxy intercepts the call and submits the method as a
RunnableorCallableto the configured thread pool (by default,SimpleAsyncTaskExecutor) - Main Thread Freed: The calling thread returns immediately without waiting
- Async Execution: The method executes on a separate thread from the pool
`@Async` and `@Transactional` Together
This is a critically important topic with three use cases. Understanding what works and what does not is a common interview question.
@Async.Use Case 1 `@Transactional` Method Calls an `@Async` Method ( Avoid)
◆ Scenario
1// Class A — caller2public class SomeClass {3 @Autowired4 private UserService userService;5
6 public void someMethod() {7 userService.updateUser(); // Calls the transactional method8 }9}1// UserService — has @Transactional, calls @Async method internally2@Service3public class UserService {4
5 @Autowired6 private BalanceService balanceService;7
8 @Transactional9 public void updateUser() {10 // These run within the transaction ✅11 updateUserStatus();12 updateFirstName();13 updateLastName();14
15 // ❌ This spawns a NEW thread — transaction context NOT carried forward16 balanceService.updateUserBalance();17 }18}1@Component2public class BalanceService {3
4 @Async5 public void updateUserBalance() {6 // Runs in a new thread — NO transaction context here7 // Any DB changes here are NOT part of updateUser's transaction8 }9}◆ The Problem
◆ Why It Fails
- The transaction is bound to Thread 1 (the main thread)
@Asynccreates Thread 2 — a brand-new thread- Thread 2 has no transaction context — it runs completely outside any transaction
- If
updateUser()fails and rolls back: updateUserStatus()is rolled back ✅updateFirstName()is rolled back ✅updateUserBalance()is NOT rolled back ❌ (it ran without a transaction on Thread 2)
Use Case 2 Same Method Has Both `@Async` and `@Transactional` ( Use With Caution)
◆ Scenario
1@Service2public class UserService {3
4 // Both annotations on the same method5 @Async6 @Transactional7 public void updateUser() {8 updateUserStatus();9 updateFirstName();10 // ... all operations11 }12}◆ What Happens
◆ Why It's Risky
A new thread is created, and that new thread does have its own transaction. So operations inside updateUser() are transactional. However:
- If the caller (Thread 1) also has a transaction, that parent transaction context is not inherited
- Propagation settings like
PROPAGATION_REQUIRED(use existing transaction if present) will not work as expected — because from Thread 2's perspective, there is no existing transaction to join - Propagation settings like
SUPPORTS,MANDATORY,NEVER, etc., will all behave as if no parent transaction exists
1// Caller with its own transaction2@Transactional3public void callerMethod() {4 userService.updateUser();5 // updateUser runs on a NEW thread with a NEW transaction6 // It does NOT participate in callerMethod's transaction7 // Propagation settings in updateUser() are meaningless here8}Use Case 3 Call `@Async` First, Then `@Transactional` Inside It ( Correct & Industry Standard)
◆ Scenario
1// Controller or Service — calls an async wrapper2@Service3public class UserController {4
5 @Autowired6 private AsyncUserService asyncUserService;7
8 public void handleRequest() {9 asyncUserService.asyncUpdateUser(); // Main thread is freed immediately10 // Main thread continues here11 }12}1// Async wrapper — spawns a new thread2@Component3public class AsyncUserService {4
5 @Autowired6 private UserService userService;7
8 @Async // Creates a new thread — main thread freed9 public void asyncUpdateUser() {10 userService.updateUser(); // Calls the transactional method11 }12}1// The actual transactional logic — runs on the new thread2@Service3public class UserService {4
5 @Transactional // Transaction starts here, on the new thread6 public void updateUser() {7 updateUserStatus();8 updateFirstName();9 updateUserBalance();10 // Everything in here is transactional ✅11 // Any failure → rollback all ✅12 }13}◆ Why This Works
◆ Advantages
| Aspect | Result |
|---|---|
| Main thread | Freed immediately, no waiting |
| Transaction | Fully functional on the new thread |
| Propagation | Works correctly within the new thread |
| Rollback | Works correctly — any failure rolls back everything |
| Isolation | Clean separation of async and transactional concerns |
@Async concern (spawning a thread) from the @Transactional concern (managing a transaction). Let @Async live in a "launcher" method and @Transactional live in the actual business logic method.Use Case Comparison Table
| Use Case | Pattern | Problem | Recommendation |
|---|---|---|---|
| 1 | @Transactional method calls @Async method | Async method runs without transaction; rollback incomplete | ❌ Avoid |
| 2 | Same method has both @Async and @Transactional | Propagation from parent transaction doesn't work | ⚠️ Use with caution |
| 3 | @Async wrapper calls @Transactional method | No issues; full transaction management on new thread | ✅ Industry standard |
`@Async` Method Return Types
Overview
When a method runs on a separate thread, the main thread needs a mechanism to retrieve the result once the async work is complete. Java provides two types for this purpose: Future and CompletableFuture.
Future is now deprecated in favor of CompletableFuture, which was introduced in Java 8. CompletableFuture is the industry standard and offers chaining, composition, and more powerful APIs. For a deep dive into these types, refer to the Java Multithreading playlist — there is a dedicated 1+ hour video on Future, Callable, and CompletableFuture.Return Type Options
| Return Type | Description | Status |
|---|---|---|
void | Fire-and-forget — no result needed | ✅ Common |
Future | Older mechanism to retrieve async result | ⚠️ Deprecated |
CompletableFuture | Modern, feature-rich async result holder | ✅ Industry standard |
Option 1 `void` Return Type (Fire and Forget)
1@Async2public void performTask() {3 // Run some work on a new thread4 // No result is returned to the caller5 System.out.println("Running on: " + Thread.currentThread().getName());6}1// Caller2public void callerMethod() {3 asyncService.performTask(); // Returns immediately4 // Main thread continues here — no way to get a result5}Use when: You don't need the result and don't need to wait for completion (e.g., sending emails, logging, notifications).
Option 2 `Future<T>` Return Type (Deprecated)
1@Async2public Future<String> performTaskAsync() {3 // Simulate long-running task4 Thread.sleep(15000); // 15 seconds5 return new AsyncResult<>("Task completed!"); // Wrap result in AsyncResult6}1// Caller2public void callerMethod() throws Exception {3 Future<String> result = asyncService.performTaskAsync(); // Returns immediately4
5 // Main thread is free here — can do other work6 System.out.println("Doing other work while async task runs...");7
8 // When you need the result — main thread WAITS here9 String output = result.get(); // BLOCKS until async method completes10 System.out.println("Result: " + output);11}◆ Key `Future` Methods
| Method | Description |
|---|---|
get() | Blocks until result is available |
get(timeout, unit) | Blocks up to specified timeout |
isDone() | Returns true if task completed |
isCancelled() | Returns true if task was cancelled |
cancel(mayInterrupt) | Attempts to cancel the task |
◆ Execution Timeline
Option 3 `CompletableFuture<T>` Return Type (Industry Standard)
1@Async2public CompletableFuture<String> performTaskAsync() {3 // Simulate long-running task4 Thread.sleep(15000);5 return CompletableFuture.completedFuture("Task completed!");6}1// Caller2public void callerMethod() throws Exception {3 CompletableFuture<String> result = asyncService.performTaskAsync(); // Returns immediately4
5 // Main thread continues freely6 System.out.println("Doing other work while task runs...");7
8 // Wait for result when needed9 String output = result.get(); // BLOCKS until completion10 System.out.println("Result: " + output);11}◆ Why CompletableFuture Over Future
| Feature | Future | CompletableFuture |
|---|---|---|
| Block for result | ✅ get() | ✅ get() |
| Non-blocking callbacks | ❌ No | ✅ thenApply(), thenAccept() |
| Chaining operations | ❌ No | ✅ Yes |
| Combining futures | ❌ No | ✅ allOf(), anyOf() |
| Manual completion | ❌ No | ✅ complete() |
| Exception handling | ❌ Limited | ✅ exceptionally(), handle() |
| Status | ⚠️ Deprecated | ✅ Industry standard |
CompletableFuture supports powerful chaining: you can chain operations like .thenApply(), .thenCompose(), .thenAccept(), etc. This allows you to build complex async pipelines without blocking. See the Java Multithreading playlist for a full in-depth explanation.Exception Handling in `@Async` Methods
This is a very important interview topic. The challenge differs based on whether the async method returns void or a Future/CompletableFuture.
Case 1 Method Returns `Future` or `CompletableFuture` (Simple)
1@Async2public CompletableFuture<String> performTask() {3 // Some exception occurs4 int result = 5 / 0; // ArithmeticException5 return CompletableFuture.completedFuture("Done");6}1// Caller2public void callerMethod() {3 CompletableFuture<String> result = asyncService.performTask();4
5 try {6 String output = result.get(); // Exception is thrown HERE7 System.out.println(output);8 } catch (ExecutionException e) {9 // The original exception is wrapped in ExecutionException10 System.err.println("Async task failed: " + e.getCause().getMessage());11 } catch (InterruptedException e) {12 Thread.currentThread().interrupt();13 }14}How it works:
- The exception is held inside the
CompletableFuture/Futureobject - When the caller calls
.get(), the exception is re-thrown wrapped inExecutionException - The caller can catch and handle it at the
get()call site
Case 2 Method Returns `void` (The Tricky One)
1@Async2public void performTask() {3 int result = 5 / 0; // ArithmeticException — how do we handle this?4}1// Caller2public void callerMethod() {3 asyncService.performTask(); // Returns immediately4 // No Future to call .get() on5 // Main thread has NO WAY to know if an exception occurred6}The exception occurs on a different thread. The main thread has already moved on. There is no reference to catch it with.
◆ Solution A Try-Catch Inside the Async Method
1@Async2public void performTask() {3 try {4 int result = 5 / 0; // Simulate exception5 // ... business logic6 } catch (Exception e) {7 // Handle here: log, alert, retry, etc.8 System.err.println("Exception in async method: " + e.getMessage());9 log.error("Async task failed", e);10 }11}Pros: Simple, straightforward. Cons: You have to add try-catch to every async void method — code duplication.
◆ Solution B Custom `AsyncUncaughtExceptionHandler` (Industry Standard)
Spring Boot provides a built-in default handler:
1// Spring Boot's built-in default (SimpleAsyncUncaughtExceptionHandler)2public class SimpleAsyncUncaughtExceptionHandler implements AsyncUncaughtExceptionHandler {3
4 @Override5 public void handleUncaughtException(Throwable ex, Method method, Object... params) {6 // Default behavior: just logs the exception7 logger.error("Unexpected exception occurred invoking async method: " + method, ex);8 }9}If you don't configure anything, Spring Boot uses this and logs the exception automatically. But you can replace it with your own.
◆ Step 1 Create a Custom Exception Handler
1@Component2public class DefaultAsyncUncaughtHandler implements AsyncUncaughtExceptionHandler {3
4 @Override5 public void handleUncaughtException(Throwable ex, Method method, Object... params) {6 // Custom handling — you define the logic7 System.out.println("=== Async Exception Caught ===");8 System.out.println("Method: " + method.getName());9 System.out.println("Exception: " + ex.getMessage());10
11 // You can also:12 // - Send an alert/notification13 // - Log to a monitoring system (Datadog, Splunk, etc.)14 // - Retry the operation15 // - Write to a dead-letter queue16 log.error("Async method [{}] threw exception: {}", method.getName(), ex.getMessage(), ex);17 }18}◆ Step 2 Register the Custom Handler via `AsyncConfigurer`
1@Configuration2@EnableAsync3public class AppConfig implements AsyncConfigurer {4
5 @Autowired6 private DefaultAsyncUncaughtHandler asyncUncaughtHandler;7
8 @Override9 public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {10 // Return your custom handler11 // Spring will use this instead of the default one12 return asyncUncaughtHandler;13 }14}◆ Step 3 The Async Method (No try-catch needed)
1@Component2public class AsyncService {3
4 @Async5 public void performTask() {6 int result = 5 / 0; // ArithmeticException — no try-catch here7 // Spring automatically routes uncaught exceptions to your handler8 }9}◆ How the Custom Handler Gets Invoked
◆ Exception Handler Configuration Diagram
◆ Comparison of Exception Handling Approaches
| Approach | Pros | Cons | Best For |
|---|---|---|---|
| Try-catch inside async method | Simple, explicit, method-level control | Duplicated in every async void method | One-off cases with unique handling |
Custom AsyncUncaughtExceptionHandler | Centralized, no duplication, clean code | Applies globally to all async void methods | Industry standard — most applications |
| Spring default handler | Zero configuration | Only logs; no custom logic | Development / debugging only |
AsyncUncaughtExceptionHandler and register it via AsyncConfigurer. This keeps async methods clean and provides a single centralized place for exception handling, logging, alerting, and retry logic.Key Observations
- Both conditions must be met for
@Asyncto work: public method + different class from caller.
@Asyncis AOP-based — the same proxy mechanism that powers@Transactionalalso powers@Async.
- Transaction context is thread-local — it never crosses thread boundaries. A new thread spawned by
@Asynchas no awareness of any transaction on the parent thread.
- Use Case 3 is the correct pattern —
@Asyncin a launcher method,@Transactionalin the actual business method, all on the new thread.
CompletableFutureis the preferred return type overFuture.Futureis deprecated.
- Exception handling differs by return type:
- With
Future/CompletableFuture— exception surfaces at.get()call - With
void— exception must be handled viaAsyncUncaughtExceptionHandleror try-catch
- Spring provides a default exception handler (
SimpleAsyncUncaughtExceptionHandler) that simply logs uncaught exceptions from async void methods.
- You can override the default handler by implementing
AsyncUncaughtExceptionHandlerand registering it viaAsyncConfigurer.
Common Mistakes
Mistake 1 Calling `@Async` From the Same Class
1// ❌ Does NOT work — same class invocation bypasses AOP proxy2@Component3public class MyService {4
5 public void caller() {6 this.asyncMethod(); // Bypasses proxy — runs synchronously7 }8
9 @Async10 public void asyncMethod() {11 // Expected: new thread. Reality: same thread.12 }13}Fix: Move asyncMethod() to a separate @Component class and inject it.
Mistake 2 Using `@Async` on a Private Method
1// ❌ Does NOT work — AOP cannot proxy private methods2@Async3private void asyncMethod() {4 // @Async has NO effect here5}6
7// ✅ Must be public8@Async9public void asyncMethod() {10 // Works correctly11}Mistake 3 Calling `@Async` Method Inside a `@Transactional` and Expecting Shared Transaction
1// ❌ WRONG ASSUMPTION: balance update is part of the transaction2@Transactional3public void updateUser() {4 updateStatus();5 balanceService.updateBalance(); // @Async — runs WITHOUT transaction!6}Fix: Use Use Case 3 pattern — @Async first, then @Transactional on the inner method.
Mistake 4 Not Handling Exceptions in `void` Async Methods
1// ❌ Exception silently disappears if no handler is configured2@Async3public void asyncTask() {4 throw new RuntimeException("This will be silently lost!");5}Fix: Implement a custom AsyncUncaughtExceptionHandler or use try-catch inside the method.
Mistake 5 Forgetting `@EnableAsync`
1// ❌ @Async annotation is completely ignored without this2@SpringBootApplication3// Missing @EnableAsync!4public class MyApp { ... }5
6// ✅ Correct7@SpringBootApplication8@EnableAsync9public class MyApp { ... }Best Practices
- Always place
@Asyncmethods in a separate@Serviceor@Componentclass from the calling code.
- Always make
@Asyncmethods public.
- Configure a custom thread pool using
ThreadPoolTaskExecutorinstead of the defaultSimpleAsyncTaskExecutor(which creates a new thread for every call, with no pooling).
1 @Bean(name = "taskExecutor")2 public Executor taskExecutor() {3 ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();4 executor.setCorePoolSize(5);5 executor.setMaxPoolSize(10);6 executor.setQueueCapacity(100);7 executor.setThreadNamePrefix("Async-");8 executor.initialize();9 return executor;10 }- Use
CompletableFutureoverFuturewhen you need to retrieve the result.
- Implement a custom
AsyncUncaughtExceptionHandlerfor centralized exception handling ofvoidasync methods — don't scatter try-catch blocks.
- Follow Use Case 3 for
@Async+@Transactional— never mix them on the same method unless you fully understand the implications, and never call an@Asyncmethod from within a@Transactionalmethod.
- Name your thread pool executors so logs clearly identify which pool executed which task.
Interview Notes
@Async in Spring Boot.Q1: What are the two conditions for `@Async` to work correctly?
Answer:
- The
@Async-annotated method must be in a different class from the caller. - The method must be public.
Both conditions exist because @Async uses Spring AOP proxies, which can only intercept public methods called from outside the class.
Q2: Why does calling an `@Async` method from the same class not work?
Answer: Spring AOP creates a proxy around the bean. When you call this.asyncMethod() from within the same class, you are calling the actual object, not the proxy. The proxy is never involved, so the AOP advice (which spawns the new thread) never executes. The method runs synchronously on the same thread.
Q3: How do `@Async` and `@Transactional` interact? What are the challenges?
Answer: Transaction context is thread-local and is never transferred to a new thread created by @Async. There are three patterns:
- Pattern 1 (Avoid): A
@Transactionalmethod calls an@Asyncmethod — the async method runs without any transaction; rollback is incomplete. - Pattern 2 (Caution): Same method has both annotations — creates a new transaction on the new thread, but parent transaction context is not inherited; propagation doesn't work as expected.
- Pattern 3 (Correct): An
@Asyncwrapper method calls a@Transactionalmethod — the transactional method runs fully on the new thread with a proper transaction.
Q4: How do you handle exceptions in an `@Async` method that returns `void`?
Answer: Two approaches:
- Try-catch inside the method — catches the exception locally; fine for one-off cases.
- Custom
AsyncUncaughtExceptionHandler— implement the interface, overridehandleUncaughtException(), and register it viaAsyncConfigurer.getAsyncUncaughtExceptionHandler(). This is the industry standard as it centralizes all async exception handling.
Q5: How do you handle exceptions in an `@Async` method that returns `CompletableFuture`?
Answer: The exception is stored inside the CompletableFuture object. When the caller calls .get(), the exception is re-thrown wrapped in ExecutionException. The caller wraps .get() in a try-catch and handles ExecutionException, accessing the original exception via e.getCause().
Q6: What is the difference between `Future` and `CompletableFuture` in the context of `@Async`?
Answer: Both allow the caller to retrieve the result of an async method. However, CompletableFuture (Java 8+) is far superior: it supports non-blocking callbacks (.thenApply(), .thenAccept()), chaining of multiple async operations, combining multiple futures (allOf(), anyOf()), and manual completion. Future is deprecated in favor of CompletableFuture.
Q7: What happens if you don't configure `AsyncUncaughtExceptionHandler`?
Answer: Spring Boot uses its built-in SimpleAsyncUncaughtExceptionHandler by default, which simply logs the exception with the message "Unexpected exception occurred invoking async method". The exception is not re-thrown and does not affect the main thread.
Summary
| Topic | Key Point |
|---|---|
| Condition 1 | @Async method must be in a different class from caller |
| Condition 2 | @Async method must be public |
| Why | AOP proxy can only intercept public cross-class method calls |
| Use Case 1 | @Transactional calls @Async → async runs without transaction ❌ |
| Use Case 2 | Same method with both → works but propagation broken ⚠️ |
| Use Case 3 | @Async wrapper → @Transactional method → industry standard ✅ |
| Transaction context | Thread-local — never transferred to new threads |
| void return | Exception handled via AsyncUncaughtExceptionHandler or try-catch |
| Future return | Exception surfaces at .get() call — use try-catch there |
| CompletableFuture | Preferred return type; richer API than Future |
| Custom handler | Implement AsyncUncaughtExceptionHandler + register via AsyncConfigurer |
| Default handler | SimpleAsyncUncaughtExceptionHandler — just logs; no custom logic |
@Async + @Transactional: Always let @Async spawn the thread first, then let @Transactional manage the transaction on that new thread. Never go the other direction.End of Study Guide — Spring Boot @Async Advanced Concepts
Mastery check
How well can you recall this?
Finished this lesson?