Path 5 · lesson 3 of 5
@Async: where the exception goes
The caller of an @Async method has already moved on when it fails. A void method leaves one log line, a future that nobody reads leaves nothing, and the default queue has no limit.
What you will learn
- Say what happens to an exception thrown by an
@Asyncmethod for each return type - Explain why the caller of a void
@Asyncmethod can never catch its exception - Name the executor Spring Boot uses for
@Asyncand its default pool and queue sizes - Recognise an
@Asyncmethod that runs on the caller's thread because of self-invocation - Install a handler so that a failed background task is counted and alerted on
Before you start
The concept
@Async works through the same kind of proxy as @Transactional. The proxy does not call your method. It hands the call to an executor as a task and returns to the caller at once. Your method then runs later, on a pool thread.
So when the method throws, the caller is no longer there to catch it. Its try block finished long ago. What happens to the exception depends only on the return type.
Returns void
- The exception goes to the
AsyncUncaughtExceptionHandler. - The default handler writes one ERROR line with the stack trace.
- Nothing else happens: no retry, no metric, no alert.
Returns CompletableFuture or Future
- The exception is stored inside the future.
- It is thrown when someone calls
join()orget(), or reaches anexceptionallystage. - If nobody reads the future, nothing is logged at all.
Why it exists
Work is made asynchronous because the caller should not wait for it: a receipt email, an audit record, a search index update, a webhook. These are exactly the tasks nobody watches. When they fail quietly, the first report comes from a customer who never received the receipt.
The second risk is the queue. With Spring Boot's defaults, tasks that arrive faster than eight threads can finish them wait in a queue with no upper limit. A slow mail server therefore does not cause errors. It causes memory to grow until the process dies, taking every queued task with it.
How it works inside
The lab calls a failing @Async method in four ways. The first line reports the executor that Spring Boot auto-configured, read from the running application.
Program outputjava -jar target/spring-production-lab-1.0.jar --demo=async (part 1: a void method)
Real JVM outputExecutor behind @Async: ThreadPoolTaskExecutor, corePoolSize=8, maxPoolSize=2147483647, queueCapacity=2147483647 1. void method. Caller is main caller: sendReceipt returned normally, no exception seen sendReceipt(41) runs on task-1 2026-11-28T12:28:43.988Z ERROR 33050 --- [spring-production-lab] [ task-1] .a.i.SimpleAsyncUncaughtExceptionHandler : Unexpected exception occurred invoking async method: public void lab.Mailer.sendReceipt(long) ... java.lang.IllegalStateException: SMTP server refused the connection
main, reports that sendReceipt returned normally. Only afterwards does the method run on task-1 and fail. The one trace of the failure is the ERROR line from SimpleAsyncUncaughtExceptionHandler, followed by the stack trace.Program outputThe same run (parts 2 to 4)
Real JVM output2. CompletableFuture method, result never read renderInvoice(42) runs on task-2 caller: nothing was logged. isCompletedExceptionally=true 3. CompletableFuture method, result read with join() renderInvoice(43) runs on task-3 caller caught java.util.concurrent.CompletionException: java.lang.IllegalStateException: template not found 4. the same void method called from inside its own class sendReceipt(44) runs on main caller caught java.lang.IllegalStateException: SMTP server refused the connection <- it ran on the caller's thread
CompletableFuture and the caller ignores it: the future completed exceptionally and nothing was logged anywhere. In part 3 the caller calls join() and receives a CompletionException wrapping the original. In part 4 the void method is called from inside its own class: it ran on main, and the caller caught the exception, because it was never asynchronous.A ThreadPoolExecutor only adds threads beyond the core size when its queue is full. With an unbounded queue that never happens, so the maximum size is irrelevant and the pool stays at 8 threads whatever the load. The numbers that matter are the core size and the queue capacity.
Architecture
Drawing diagram…
A flowchart. The caller thread calls the async proxy, which submits a task to an unbounded queue and returns at once. Eight pool threads take tasks from the queue. If a void method throws, the exception goes to the uncaught exception handler, which logs one error line. If a method returning a future throws, the exception is stored in the future, and reaches whoever reads it, or is lost if it is never read.
flowchart LR
C["Caller thread"] -->|"sendReceipt()"| P["@Async proxy"]
P -->|"submit task, return at once"| Q["Queue, unbounded by default"]
Q --> W["8 pool threads: task-1 to task-8"]
W -->|"void method throws"| H["AsyncUncaughtExceptionHandler: one ERROR line"]
W -->|"future method throws"| F["Stored in the CompletableFuture"]
F -->|"join() or exceptionally"| R["Whoever reads it"]
F -->|"never read"| N["Lost"]- The proxy returns as soon as the task is queued. Nothing the task does afterwards can reach the caller's stack.
- The queue is the hidden state. Its length is the amount of work the service has accepted and not done, and by default nothing limits or reports it.
Step by step
Drawing diagram…
A sequence diagram. The request thread calls sendReceipt on the proxy, which submits a task to the executor and returns immediately, so the customer gets a 200 response. Later the executor runs the task on thread task-1, it throws, and the uncaught exception handler logs an error. Nobody is told.
sequenceDiagram
participant C as Request thread
participant P as Proxy
participant E as Executor
participant T as task-1
participant H as Uncaught handler
C->>P: sendReceipt(41)
P->>E: submit task
P-->>C: returns immediately
Note over C: responds 200 to the customer
E->>T: run sendReceipt(41)
T->>T: throws IllegalStateException
T->>H: handleUncaughtException
H->>H: log ERROR
Note over C,H: nobody is told- The customer has a success response before the email is attempted. A design that needs the email to be sent cannot rest on
@Asyncalone. - The handler is the last place where the failure is still visible. If it only logs, the failure rate of background work is unknown.
In a real system
A failed task is gone. @Async keeps tasks in memory, so there is no retry, and a restart or a deploy drops everything still queued. For work that must happen, such as a payment notification, store the intent first: an outbox row or a message on a queue, processed by something that can retry.
- Context does not follow the task. The pool thread has no transaction, no security context and no logging MDC from the caller. A
TaskDecoratorcan copy the last two; a transaction cannot be carried over. - Entities do not survive the hop. A JPA entity passed to an
@Asyncmethod is detached there. Pass ids and load again inside the task. - Shutdown drops the queue. Set
spring.task.execution.shutdown.await-terminationand a period so that a deploy lets running and queued tasks finish.
Queueing and utilisation
Simulation, not a real clusterWhy a queue in front of a fixed number of workers grows without limit once arrivals approach what the workers can finish.
Step 1 · The pattern
Half busy, short queue
One server handles one request at a time: most take 200 ms, one in five takes 1.5 s (a cache miss, a big page), so it can serve about 2.2 a second. Requests arrive at random, 1.1 a second: the server is busy about 50% of the time. Sometimes two or three arrive together and wait briefly, and the idle moments clear them. (All numbers are illustrative.)
- request
- served
Java and Spring Boot
A handler that makes failed background tasks visible, and an executor with a bounded queue. AsyncConfigurer is the hook Spring reads both from.
@Configuration@EnableAsyncclass AsyncConfig implements AsyncConfigurer { private static final Logger log = LoggerFactory.getLogger(AsyncConfig.class); private final MeterRegistry meters; AsyncConfig(MeterRegistry meters) { this.meters = meters; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return (ex, method, params) -> { meters.counter("async.failures", "method", method.getName()).increment(); log.error("Async task {} failed", method.toGenericString(), ex); }; }}Why it is written this way
- The handler is called only for methods that return
void. Methods that return a future never reach it. - A counter turns silent failures into a number that can have an alert. One log line among thousands does not.
spring.task.execution.pool.core-size=8spring.task.execution.pool.max-size=16spring.task.execution.pool.queue-capacity=200spring.task.execution.shutdown.await-termination=truespring.task.execution.shutdown.await-termination-period=30sWhy it is written this way
- With a bounded queue the pool can grow to its maximum, and a full pool rejects new tasks with
TaskRejectedExceptionin the caller, where it can be handled. - A rejection is a signal you can see and act on. An unbounded queue hides the same overload until memory runs out.
Wrong, then right
An invoice is rendered in the background. The incorrect version returns a future and drops it. The corrected version attaches the failure handling to the future.
Incorrect implementation
@Serviceclass InvoiceRenderer { @Async public CompletableFuture<String> render(long orderId) { return CompletableFuture.completedFuture(template.apply(orderId)); }}@RestControllerclass InvoiceController { @PostMapping("/orders/{id}/invoice") void create(@PathVariable long id) { renderer.render(id); // the future is dropped }}Why it is written this way
- Returning a future looks more careful than returning void. Dropped, it is less visible than void.
Why it fails
- When
template.applythrows, Spring completes the returned future exceptionally. The uncaught exception handler is not called, because the method does not return void. - Nobody holds the future, so nobody ever asks it for a result. Part 2 of the lab shows the outcome: the task failed and not one line was logged.
Corrected implementation
@RestControllerclass InvoiceController { @PostMapping("/orders/{id}/invoice") void create(@PathVariable long id) { renderer.render(id).whenComplete((path, ex) -> { if (ex != null) { failures.increment(); log.error("Invoice for order {} failed", id, ex); } }); }}Why it is written this way
whenCompleteruns for success and failure alike, so the failure is logged and counted even though the request thread does not wait.
Trade-offs
- Every caller has to remember to attach the handling. A void method with a global handler cannot be forgotten in the same way.
- The failure is now visible, but the invoice is still not rendered. Work that must succeed needs a durable record and a retry, which
@Asyncdoes not provide.
Configuration
The properties behind Spring Boot's applicationTaskExecutor. The defaults are the ones the lab printed.
spring.task.execution.pool.core-sizeDefault 8
- What it does
- Threads kept in the pool. With an unbounded queue this is also the most that will ever run.
- When to change it
- Size it from how many tasks may run at once against the slowest thing they call, not from the CPU count alone.
spring.task.execution.pool.queue-capacityDefault unbounded
- What it does
- How many tasks may wait. Unbounded means the queue is limited only by the heap.
- When to change it
- Set a limit so that overload shows up as rejections you can count.
spring.task.execution.pool.max-sizeDefault unbounded
- What it does
- Upper limit of threads. It only takes effect once the queue is full.
- When to change it
- Set it together with the queue capacity. On its own it changes nothing.
spring.task.execution.thread-name-prefixDefault task-
- What it does
- Prefix of the pool's thread names, as seen in logs and thread dumps.
- When to change it
- Keep it recognisable, so that a thread dump shows at a glance which threads run background work.
Hands-on exercise
Lose an exception, then find it
Run the four calls, then make the silent one visible.
Steps · 0 of 4 done
What you should see
Part 2 now prints the IllegalStateException. With the extra arguments the first line reports corePoolSize=1 and queueCapacity=1, which shows that the properties configure the executor behind @Async.
What can go wrong
try and catch around the call
- Symptom
- A
catchblock around a call to a void@Asyncmethod never runs, although the task fails. - Cause
- The call returns as soon as the task is queued. The exception is thrown later, on another thread.
- Fix
- Handle the failure inside the task, in the uncaught exception handler, or on the returned future.
@Async called from the same class
- Symptom
- The request takes as long as before, and the stack trace shows the request thread inside the supposedly asynchronous method.
- Cause
- Self-invocation: the call on
thisdoes not pass the proxy, so the method runs synchronously. - Fix
- Move the method to its own bean and call it through the injected reference.
An unbounded queue in front of a slow dependency
- Symptom
- Heap use climbs for hours while the mail provider is slow, then the process is killed for memory.
- Cause
- Tasks arrive faster than 8 threads finish them and the default queue accepts all of them.
- Fix
- Bound the queue, alert on rejections and on queue length, and put a timeout on the call the tasks make.
How to troubleshoot
Background work sometimes does not happen and nothing is alerting
Check
Search the logs for "Unexpected exception occurred invoking async method"
- How to read it
- That is the line of the default handler for void methods. Its absence proves nothing for methods that return a future.
Not sure whether a method really runs asynchronously
Check
Log Thread.currentThread().getName() inside the method
- How to read it
- A name starting with
task-is the Spring Boot executor. A name such ashttp-nio-8080-exec-3means the method ran on the caller's thread.
Memory grows while a downstream system is slow
Check
The executor.queued and executor.active metrics, or a heap histogram
- How to read it
- A queued count that keeps rising with active stuck at the core size is a backlog. In a histogram it shows as a large number of task objects held by a
LinkedBlockingQueue.
Key takeaways
- The caller of an
@Asyncmethod has returned before the method runs, so it can never catch what the method throws. - A void method sends its exception to the
AsyncUncaughtExceptionHandler, which by default only logs. A future keeps it until someone reads the future. - Spring Boot's default executor has 8 threads and an unbounded queue. Overload shows up as memory growth, not as errors.
- A call from inside the same class is not asynchronous at all.
@Asyncgives no retry and no durability. Work that must happen needs a stored record of the intent.
Practical check
Small scenarios, one decision each. Pick what you would do, then read why.
Scenario 1 of 2
notifyWarehouse(order) is a void @Async method. The controller calls it inside try { ... } catch (Exception e) { return 500; } and then returns 200. The warehouse API is down, so the method throws on every call.
What does the customer see, and what records the failure?
Scenario 2 of 2
A service queues about 50 @Async email tasks per second with Spring Boot's default executor. Each task normally takes 100 ms. The mail provider slows down and each task now takes 2 seconds.
What happens over the next hour?
References
References: Spring Framework reference: Task execution and scheduling (@Async, return types, exception management with @Async) ↗ · Spring Boot reference: Task execution and scheduling (applicationTaskExecutor, default of 8 core threads, virtual threads) ↗ · Java SE 21 API: ThreadPoolExecutor (threads beyond the core size are added only when the queue is full) ↗ · Report a problem