Video in progress
How do you shut down an ExecutorService gracefully, especially in Kubernetes?
First you stop accepting new tasks with shutdown(), wait for a bounded time with awaitTermination, then send an interrupt with shutdownNow(). The whole process has to be shorter than the pod's terminationGracePeriodSeconds.
📖 Answer
The standard pattern:
void stop(ExecutorService pool) {
pool.shutdown(); // new tasks are rejected
try {
if (!pool.awaitTermination(20, TimeUnit.SECONDS)) {
List<Runnable> dropped = pool.shutdownNow(); // interrupt + the queued ones come back
log.warn("{} ta task bajarilmay qoldi", dropped.size());
if (!pool.awaitTermination(5, TimeUnit.SECONDS)) {
log.error("pool to'xtamadi");
}
}
} catch (InterruptedException e) {
pool.shutdownNow();
Thread.currentThread().interrupt();
}
}
In Java 19+, ExecutorService is AutoCloseable, and close() works similarly, but it waits for the tasks indefinitely.
In Kubernetes the timing matters. When a pod is deleted, SIGTERM arrives, and when terminationGracePeriodSeconds (default 30 s) runs out, SIGKILL follows. Inside that window:
- in Spring Boot,
server.shutdown=gracefulandspring.lifecycle.timeout-per-shutdown-phaselet in-flight HTTP requests finish; - on a Spring-managed
ThreadPoolTaskExecutor,setWaitForTasksToCompleteOnShutdown(true)andsetAwaitTerminationSeconds(...); - for pools you create yourself, the code above inside
@PreDestroyor aSmartLifecycle.
What's often forgotten:
- if tasks don't respond to interrupts,
shutdownNow()does nothing; - the list returned by
shutdownNow()is lost, so for important work you have to send it back to the DB or a queue; - better yet, make tasks idempotent and keep the state outside: then even SIGKILL doesn't lose data, it only causes a re-run.
Sign up to mark studied questions and save your progress.