Video in progress
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()aftershutdown(), you get aRejectedExecutionException; - if you never shut the executor down, its non-daemon threads won't let the JVM exit. A plain
mainprogram "hangs".
In Spring, the ThreadPoolTaskExecutor bean is shut down by the container itself; with setWaitForTasksToCompleteOnShutdown(true) you get behavior similar to the first option.
Sign up to mark studied questions and save your progress.