Executors and thread pools question 82 of 180 mid
What is the difference between shutdown() and shutdownNow(), and how do you shut down properly?
shutdown()kills threads immediately- Correct:
shutdown()stops accepting work and drains the queue;shutdownNow()also interrupts running tasks and returns the queued ones - They are identical
shutdownNow()waits for tasks to finish
shutdown() is graceful: no new submissions, everything already queued still runs. shutdownNow()
tries to stop immediately: it drains the queue, returns the tasks that never ran, and interrupts the
workers. Interrupt is cooperative, so a task that ignores interruption keeps going regardless.
Neither method waits. The complete idiom:
pool.shutdown();
if (!pool.awaitTermination(30, SECONDS)) {
pool.shutdownNow();
if (!pool.awaitTermination(30, SECONDS)) {
log.error("pool did not terminate");
}
}
A non-daemon pool that is never shut down keeps the JVM alive after main returns, which is a common cause of a process that will not exit.
Quiz yourself on Executors and thread pools Suggest a correction