This English version was translated by Claude.
waitForTasksToCompleteOnShutdown(true) on an @Async pool (the thread pool that runs the tasks @Async hands off), the pool waits for remaining work in ③ Bean destroy. By then, the Redis connection has already been closed in ② lifecycle stop.awaitTermination is neither interrupted nor waited for; it is simply left running. The "next task" handed to a pool that has closed intake is rejected inside the after-commit callback, and it disappears with only one log line outside the catch.@Async pools together with graceful shutdownThreadPoolTaskExecutor they use all the timePart 1 confirmed with logs that Spring shuts down in the order
① shutdown event→② lifecycle stop→③ Bean destroy. See Part 1 for the details of the order.
① shutdown event→ the stage that announces shutdown has started② lifecycle stop→ the stage that stops beans in turn, starting from the bean with the largest phase number (a phase is a number for the stop order, and a larger one stops first)③ Bean destroy→ the stage that closes the remaining beans in the reverse of the order they were created- Redis connection → the connection that sends requests to Redis, the cache store. This connection stops in
②
This post answers the two questions Part 1 left open.
At which stage does an
@Asyncpool wait for remaining work?
When the setting that waits for task completion is on, is the Redis connection still alive while the tasks wait?
| Term | Meaning |
|---|---|
| intake | the pool accepting new tasks |
awaitTermination | the setting for the maximum time the pool waits for tasks at shutdown |
The service environment and the settings that were already on are as follows.
| Item | Value |
|---|---|
| Version | Spring Boot 3.5 (Spring Framework 6.2, Spring Data Redis 3.5) |
| Infrastructure | AWS ECS (a container execution service, on EC2), with an ALB (Application Load Balancer, a load balancer that distributes requests) in front. SIGKILL (forced termination) 30 seconds after SIGTERM (the shutdown request signal) |
| Settings already on | server.shutdown: graceful · spring.lifecycle.timeout-per-shutdown-phase: 35s |
| Post-processing | After commit, @TransactionalEventListener(AFTER_COMMIT) (a listener called after the commit) + @AsyncCache eviction (Redis), publishing the creation task to MQ, updating DB state, and so on |
| Async pool | ThreadPoolTaskExecutor |
timeout-per-shutdown-phase: 35sis the upper limit for waiting in a single phase. Forced termination comes 30 seconds after SIGTERM (the ECS stopTimeout), so the limit (35 seconds) is longer than the forced-termination time.
SIGKILL can arrive before a phase has used up its limit.
During deployments, post-commit asynchronous tasks were disappearing. We added settings to prevent that.
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(30);⭐⭐ In this post, the two lines above, which we added so the pool waits for remaining tasks at shutdown, are called the 'wait setting'!
It is a different setting from server.shutdown: graceful. Graceful is the setting where the web server waits for HTTP requests, and the wait setting is the one where the @Async pool waits.
A pool with the default values, without the setting, also waits for tasks that are running (see the table below). The name refers to a pool with the two lines above turned on.
We continue using the test bed from Part 1.
The experiment code is in stage2~6 and the SIGTERM demo of the Spring Shutdown Playground.
timeline prefix is omitted, and indented lines are tasks inside a pool.| Real code | Shutdown behavior |
|---|---|
LettuceConnectionFactory | Stops at ② lifecycle stop phase 0 and rejects connections afterward |
Rabbit CachingConnectionFactory | Drops the connection at ② lifecycle stop phase MIN and reconnects on the next request |
HikariDataSource | close() at ③ Bean destroy |
Without the setting above, does nobody wait for asynchronous tasks?
There is a setting called server.shutdown: graceful.
From the name, it sounds like server shutdown waits for requests, and this setting works as follows.
server.shutdown: graceful is handled in the lifecycle at phase MAX − 1024.@Async after commit runs in a different thread pool=> What happens to asynchronous tasks at shutdown is decided by the pool's own settings.
ThreadPoolTaskExecutor changes with each settingThe default value of waitForTasksToCompleteOnShutdown is false.
So at first I thought, "with the default, the pool closes as soon as the shutdown event arrives, and remaining tasks are rejected."
Most articles you find by searching also explain that "by default, running tasks are interrupted."
But when I checked in Spring 6.2's ThreadPoolTaskExecutor, it behaved somewhat differently.
The articles are not wrong. Up to 6.0, ③ Bean destroy cut tasks off immediately with shutdownNow().
From 6.1, it waits once before cutting them off.
That is because ThreadPoolTaskExecutor became a SmartLifecycle.
The default phase was Integer.MAX_VALUE in 6.1, and it is MAX / 2 from 6.2.
So all three stages from Part 1 have something to do, and it varies with the setting.
| Setting | ① shutdown event | ② lifecycle stop (MAX / 2) | ③ Bean destroy |
|---|---|---|---|
| Default | Only marks it, intake stays open | Waits until running tasks finish | Cancels the queue, requests interruption of running tasks ( shutdownNow()) |
| Wait setting | Only marks it, intake stays open | Skipped | Closes intake and waits for remaining tasks ( awaitTermination), one pool after another |
② stop waits for running tasksThe figure below shows what ①, ②, and ③ each do with the default.

① only leaves the markShutdown() mark.② turns on paused and holds off the callback until the number of running tasks reaches 0.③ cancels the queue with shutdownNow() and interrupts the running tasks.=> With the default, the pool does not close intake even when the shutdown event arrives.
[ 11ms] [Test worker] ② pool-a lifecycle stop started
[ 512ms] [pool-a-1 ] task a1 finished
[ 512ms] [pool-a-1 ] ② pool-a lifecycle stop finished
[ 513ms] [Test worker] ② redis(phase 0) stop
[ 513ms] [Test worker] ③ destroy stage startedReproduce with: ./gradlew s2 --tests '*waitsForRunningTaskInLifecycle' · test code
② lifecycle stop, while Redis is alive.[ 10ms] [Test worker] ② pool-a lifecycle stop started
spring Shutdown phase 1073741823 ends with 1 bean still running after timeout of 1000ms: [poolA]
[ 1020ms] [Test worker] ② redis(phase 0) stop ← on to the next phase after 1 second
[ 1021ms] [Test worker] ③ pool-a destroy started
[ 1021ms] [pool-a-1 ] task a1 interrupted ← shutdownNow() of ③Reproduce with: ./gradlew s2 --tests '*interruptsTaskLongerThanPhaseTimeout' · test code
=> The default was better than I expected. Up to the phase timeout, it waits for running tasks instead of cutting them off immediately.
③ Bean destroy, tasks left in the queue are cancelled, and running tasks may be interrupted.Reproduce with: ./gradlew s2 --tests '*doesNotWaitForQueuedTask' · test code
=> "0 running" is a single instant. A task that comes out of the queue after that is interrupted in ③.
The figure below shows the moment, with a1 (200ms) running and a2 (1.5 seconds) in the queue,
when ② waits only for a1 and moves on.

waitForTasksToCompleteOnShutdown(true)It skips ② and only closes intake in ③.
What if we turn on executor.setWaitForTasksToCompleteOnShutdown(true);?
It takes the if branch. (The default is the else side.)
// ExecutorConfigurationSupport.shutdown() — called by destroy() of ③ (logging omitted)
if (this.waitForTasksToCompleteOnShutdown) {
this.executor.shutdown();
}
else {
for (Runnable remainingTask : this.executor.shutdownNow()) {
cancelRemainingTask(remainingTask);
}
}
awaitTerminationIfNecessary(this.executor);
① only leaves the lateShutdown = true mark → intake stays open.stop(callback) of ② looks at lateShutdown and calls callback.run() right away → it does not wait.③ is the if side of the shutdown() above → executor.shutdown() closes intake only, and the queue keeps running.The Javadoc says the same.
The executor will not go through a coordinated lifecycle stop phase then but rather only stop and wait for task completion on its own shutdown.
-> With the setting on, the pool does not stop during the time when everything stops together; it just passes through.
It stops in its own cleanup turn and waits for tasks to finish.
=> It skips ② lifecycle stop and waits in ③ Bean destroy.
To check, what if we put one 1.5-second task into each of 2 pools, set awaitTermination to 1 second, and run the test?
[ 13ms] ② pool-a lifecycle stop started
[ 13ms] ② pool-a lifecycle stop finished ← same ms. It does not wait
[ 13ms] ② redis(phase 0) stop ← Redis stops while the task is runningReproduce with: ./gradlew s2 --tests '*waitsInDestroyOnePoolAtATime' · test code
awaitTerminationIt is the upper limit on how long ③ holds the shutdown thread.
// spring-context 6.2 — last line of ③ shutdown() (summary)
private void awaitTerminationIfNecessary(ExecutorService executor) {
if (this.awaitTerminationMillis > 0) {
if (!executor.awaitTermination(this.awaitTerminationMillis, TimeUnit.MILLISECONDS)) {
// That's it. There is no shutdownNow()
logger.warn("Timed out while waiting for executor ... to terminate");
}
}
}If you give only awaitTermination, without the waitForTasksToCompleteOnShutdown flag,
③ interrupts with shutdownNow() and then waits that long for the threads to get out.
Here is the latter part of the log from the two-pool experiment above.

[ 13ms] ③ pool-b destroy started ← reverse creation order: pool-b first
spring Timed out while waiting for executor 'poolB' to terminate
[ 1019ms] ③ pool-b destroy finished ← after 1 second. The task was not cut off
[ 1020ms] ③ pool-a destroy started ← starts only after waiting out pool-b entirely
[ 1515ms] task a1 finished
[ 1515ms] task b1 finished ← it exceeded 1 second but was not cut off③ Bean destroy → by then, Redis has already stopped in ② lifecycle stop.This is the part that confused me most at first.
awaitTermination is 1 second, but what if 1.5 seconds of work remain when ③ starts?
[ 135ms] [Test worker] ③ pool-a destroy started
spring Timed out while waiting for executor 'poolA' to terminate
[ 1138ms] [Test worker] ③ pool-a destroy finished ← after 1 second it gives up waiting and moves to the next bean
[ 1139ms] [Test worker] ③ db close
[ 1139ms] [Test worker] ③ redis destroy
[ 1640ms] [pool-a-1 ] task A finished ← it finished on its own after the resources were all closedReproduce with: ./gradlew s4 --tests '*waitForTasksTimeoutWhileChainedTaskIsRunning' · test code
awaitTermination returns false and Spring only leaves a warn log → it does not call shutdownNow(), so A is not interrupted (task A interrupted was not printed).=> awaitTermination N seconds is the maximum time the shutdown thread waits, not the deadline of the task.
The figure below shows how pool-a destroy and task A overlap on the time axis during the 1 second of awaitTermination.

task A finishedwas printed in the test because the test waits separately for the pool thread aftercontext.close().
With a real SIGTERM, the moment the shutdown hook (context.close()) finishes, the JVM stops, and the remaining tasks are cut off with neither an interrupt nor afinally.
Then what happens when an async pool uses external resources (DB, MQ, Redis)?
To test this, we put in a task that writes to each external resource once at the moment waiting begins in ③ Bean destroy.
real redis → failed IllegalStateException: LettuceConnectionFactory has been STOPPED. Use start() to initialize itReproduce with: ./gradlew s5 --tests '*waitForTasksWithRealLettuce' (requires Docker) · test code
Here is a summary of the results by setting.
| Setting | Redis | MQ | DB |
|---|---|---|---|
Default (waits in ②) | Success | Success | Success |
Wait setting (waits in ③) | Failure | Success (reconnect) | Success |
| Wait setting + DataSource created later than the pool | Failure | Success | Failure |
The DB succeeding is a coincidence.
③ Bean destroy runs in reverse creation order.→ If the DataSource is created later than the Async pool, even the DB fails.
Reproduce with: ./gradlew s3 --tests '*waitForTasksModeWithDataSourceCreatedLater' · test code
There are quite a few articles saying "handle asynchronous tasks with waitForTasksToCompleteOnShutdown(true) + setAwaitTerminationSeconds()." But the effect can vary with the Spring version and the shutdown order of beans.
| Spring Data Redis | Stage where Redis closes | Redis when the pool waits in ③ |
|---|---|---|
| 3.1.x | ③ Bean destroy | Alive if the pool is destroyed first |
| 3.2.x and later | ② lifecycle stop | Already stopped |
③ Bean destroyawaitTermination.② lifecycle stop③, Redis has already stopped.=> By the destroy stage, resources that use Lifecycle may already have been shut down.
The two settings alone can make tasks wait without being cut off, but the tasks may end up running without the external resources they need.
Earlier we said that a pool with the wait setting closes intake with shutdown() in ③
and waits for running tasks during awaitTermination.
What if that task is a chain that hands off the next task?
In real services, chains where one asynchronous task hands off the next are common.
Here, when CreateTask saves a task and commits,
ProduceTask picks it up and puts it into the Redis queue and MQ.

CreateTask is @Async + @TransactionalProduceTask is an @TransactionalEventListener(AFTER_COMMIT) listenerafterCompletion callback after commit.ProduceTask is also @AsyncProduceTask) is done by Spring's after-commit callback, not by my code.createTask has already finished, so it cannot catch it.)When pool-a's turn comes, the order is as follows.
shutdown().awaitTermination, the running CreateTask keeps going and commits.ProduceTask to the same pool-aTaskRejectedException.
[ 19ms] [Test worker] ③ pool-a destroy started
[ 20ms] [pool-a-1 ] submit B
[ 20ms] [pool-a-1 ] submit B rejected (TaskRejectedException)Reproduce with: ./gradlew s4 --tests '*waitForTasksRejectsChainedTask' · test code
=> The wait setting lets the first task (CreateTask) run to the end, and rejects the next task (ProduceTask).
This exception is raised inside the AFTER_COMMIT callback, so it leaves only a log and disappears.
// TransactionSynchronizationUtils.invokeAfterCompletion (spring-tx 6.2)
try {
synchronization.afterCompletion(completionStatus);
} catch (Throwable ex) {
// swallow it
logger.error("TransactionSynchronization.afterCompletion threw exception", ex);
}Running it with real Redis, RabbitMQ, and PostgreSQL,
the task was created in the DB but is not in the queue, and the request state is still REQUESTED.
No error state is recorded, and the only trace left is a single ERROR log line from Spring.
Reproduce (requires Docker): ./gradlew s6 --tests '*waitForTasksProduceAfterCommit' · test code
② lifecycle stopBased on everything so far, each of the two settings was only half right.
②, so Redis is alive. But it only waits for running tasks, and the queue and the next task are cut off in ③ destroy.③ destroy, so Redis has already stopped, and the next task handed off while waiting is rejected.=> What we want to solve is the combination of the two. Before the external resources stop, wait until the queue and the next tasks are finished.
To keep the resources a task uses alive, we have to follow the order in the Part 1 phase table as is.
Stop the side that produces work → drain the side that processes work (the pool) → stop the resources the work uses
=> That spot is between MAX / 2 and 0 on the phase ladder.

The code below is sample code for reference.
/**
* After the web server and listeners stop, drain the pools before Redis (phase 0) stops.
* It does not close intake, and waits until all pools are observed consecutively as "0 running + 0 queued".
*/
public class IdleDrainLifecycle implements SmartLifecycle {
private static final int REQUIRED_IDLE_CHECKS = 2;
// Fields (pools, timeout, running), constructor, start(), isRunning() omitted
@Override
public int getPhase() {
return ExecutorConfigurationSupport.DEFAULT_PHASE - 1;
}
@Override
public void stop() {
long deadline = System.nanoTime() + timeout.toNanos();
int idleStreak = 0;
while (System.nanoTime() < deadline && idleStreak < REQUIRED_IDLE_CHECKS) {
idleStreak = allIdle() ? idleStreak + 1 : 0;
sleep(20);
}
if (idleStreak < REQUIRED_IDLE_CHECKS) {
log.warn("Timed out waiting for async pools to shut down …");
}
running = false;
}
private boolean allIdle() {
return pools.stream().allMatch(pool -> {
ThreadPoolExecutor executor = pool.getThreadPoolExecutor();
return executor.getActiveCount() == 0 && executor.getQueue().isEmpty();
});
}
}Full implementation: IdleDrainLifecycle.java
Reading the code from the top, it goes like this.
getPhase() is MAX/2 − 1MAX/2) and Redis (0): after the producers stop and before Redis stops.stop() holds the shutdown thread and checks allIdle() every 20msallIdle() only checks that the number of running tasks (getActiveCount()) and the queue are both 0 for every pool③ Bean destroy.REQUIRED_IDLE_CHECKS)deadline passes, it leaves only a warn and finishesFor the pool settings, keep waitForTasksToCompleteOnShutdown(true) as is and remove only setAwaitTerminationSeconds.
awaitTermination gets rid of the wait where ③ blocked on each pool in turn → the wait is handled by the drain in ②. shutdown() is still called in ③ as before.[ 14ms] [Test worker] ② drain(idle wait) started
[ 16ms] [pool-a-1 ] submit B
[ 17ms] [pool-a-1 ] task B started
[ 322ms] [pool-a-1 ] B redis → success
[ 377ms] [Test worker] ② drain(idle wait) finished ← after B finished too
[ 378ms] [Test worker] ② pool-a lifecycle stop started
[ 378ms] [Test worker] ② redis(phase 0) stopReproduce with: ./gradlew s4 --tests '*idleDrainRunsChainedTask' · test code
With real Lettuce: ./gradlew s5 --tests '*idleDrainWithRealLettuce' · test code
With a real SIGTERM, put a task that calls Redis every 400ms into the pool and send the shutdown signal.
# with setWaitForTasksToCompleteOnShutdown + setAwaitTerminationSeconds
[ 1216ms] [pool-a-1 ] redis call #4 → success
>>> kill -TERM
[ 1330ms] [SpringContextShutdownHook] ② redis(phase 0) stop → connections rejected afterward
[ 1330ms] [SpringContextShutdownHook] ③ pool-a destroy started
[ 1619ms] [pool-a-1 ] redis call #5 → failure … has been STOPPED
… all fail through call #8
# IdleDrain
>>> kill -TERM
[ 1387ms] [SpringContextShutdownHook] ② drain(idle wait) started
[ 1622ms] [pool-a-1 ] redis call #5 → success
… all succeed through call #8
[ 3287ms] [SpringContextShutdownHook] ② drain(idle wait) finished
[ 3289ms] [SpringContextShutdownHook] ② redis(phase 0) stopReproduce with: ./scripts/02-sigterm-demo.sh wait · ./scripts/02-sigterm-demo.sh drain · script
Same task, same SIGTERM, but
with the wait setting, every Redis call after the shutdown signal failed, and with IdleDrain, every one succeeded.
The figure below puts the Redis call results of the wait setting and IdleDrain side by side, aligned to the same SIGTERM moment.

The figure and table below gather, in one place, where the default, the wait setting, and IdleDrain wait for the pool, and what happens to the next task.

| Approach | Where it waits for the pool | Next task handed off during shutdown | That task's Redis call |
|---|---|---|---|
| Default | ② MAX / 2 — until the instant running reaches 0 | Accepted | Not waited for |
| Wait setting | ③ — one pool after another | Accepted if before its own destroy, rejected if after | Fails in ③ / not executed |
| IdleDrain | ② MAX/2 − 1 — until the pool is empty | Accepted | Success |
strictEarlyShutdown(true) in the figure is an option that closes intake right at the shutdown event,
and this post does not cover it.
No.
IdleDrain is an experiment confirming that if you move the place where we wait to before the external resources,
even tasks that enter the chain can be saved.
Three things keep us from using it as is as the answer in production code.
So the answer depends on the nature of the task.
The conclusions from this post are as follows.
@Async pool waits is decided by the pool's settings, not by graceful.awaitTermination, in ③ where Redis has already stopped, and the next task handed off in the meantime disappears with a single log line.Let us doubt even the settings that seem obvious, and dig into them.
A trivial setting can cause unintended changes or behavior!
ExecutorConfigurationSupport, ExecutorLifecycleDelegate, ThreadPoolTaskExecutor, TransactionSynchronizationUtils, TransactionalApplicationListenerSynchronizationHow Does Spring Shut Down? — Analyzing the Three Shutdown Stages
The 400 I Mistook for a CORS Error — Logging Requests Rejected by Tomcat with a Valve
Strong ETags and Compression in Spring Boot (Tomcat)
Upgrading to Spring Boot 3.5 Broke Our multipart Requests