Video in progress

Strong Junior 🧵 Concurrency

What is the difference between shutdown() and shutdownNow() in ExecutorService?

shutdown() stops accepting new tasks, but finishes the queued and running ones. shutdownNow() drains the queue, returns the list of tasks that never ran, and sends an interrupt to the running threads.

📖 Answer

Neither blocks; both return right away. To wait for completion you need awaitTermination. A typical "graceful shutdown" looks like this:

void stop(ExecutorService pool) {
    pool.shutdown();
    try {
        if (!pool.awaitTermination(30, TimeUnit.SECONDS)) {
            List<Runnable> dropped = pool.shutdownNow();
            log.warn("{} ta vazifa bajarilmay qoldi", dropped.size());
            pool.awaitTermination(10, TimeUnit.SECONDS);
        }
    } catch (InterruptedException e) {
        pool.shutdownNow();
        Thread.currentThread().interrupt();
    }
}

What to watch out for:

  • shutdownNow() doesn't forcibly kill threads either. If a task ignores the interrupt, it keeps running;
  • if you submit() after shutdown(), you get a RejectedExecutionException;
  • if you never shut the executor down, its non-daemon threads won't let the JVM exit. A plain main program "hangs".

In Spring, the ThreadPoolTaskExecutor bean is shut down by the container itself; with setWaitForTasksToCompleteOnShutdown(true) you get behavior similar to the first option.