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=graceful and spring.lifecycle.timeout-per-shutdown-phase let in-flight HTTP requests finish;
  • on a Spring-managed ThreadPoolTaskExecutor, setWaitForTasksToCompleteOnShutdown(true) and setAwaitTerminationSeconds(...);
  • for pools you create yourself, the code above inside @PreDestroy or a SmartLifecycle.

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.