Graceful Shutdown of Spring Boot ThreadPoolTaskScheduler to Prevent Redis Errors
This article explains why asynchronous @Async tasks using a custom ThreadPoolTaskScheduler can fail during application shutdown due to premature Redis connection pool destruction, and provides a step‑by‑step solution using Spring's shutdown configuration to wait for tasks to complete before closing resources.
Problem Description
When using @Async with a custom ThreadPoolTaskScheduler, shutting down the application may cause asynchronous tasks that still access Redis to fail because the Redis connection pool is destroyed before the tasks finish, resulting in a JedisConnectionException.
Reproducing the Issue
Define a ThreadPoolTaskScheduler bean, create async methods that depend on StringRedisTemplate, and write a test that submits many tasks in a loop and calls System.exit(0) after the last iteration to simulate abrupt shutdown. The stack trace shows errors from the Redis connection pool.
Root Cause Analysis
The thread pool is closed without waiting for running tasks, so Redis resources are released while tasks are still executing.
Solution
Configure the ThreadPoolTaskScheduler to wait for tasks on shutdown:
@Bean("taskExecutor")
public Executor taskExecutor() {
ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
executor.setPoolSize(20);
executor.setThreadNamePrefix("taskExecutor-");
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
return executor;
}The key method setWaitForTasksToCompleteOnShutdown(true) ensures that the scheduler finishes all submitted tasks before the Spring context destroys other beans such as the Redis connection pool. The setAwaitTerminationSeconds(60) limits the waiting time to avoid indefinite blocking.
Complete Example
The full source code, including the task class, configuration, and test, is available in the SpringBoot‑Learning repository (GitHub/Gitee).
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
