I am following the standard process that was recommended by oracle to shut down the executor services. here is the code that was recommended:
void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
pool.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(60, TimeUnit.SECONDS))
System.err.println("Pool did not terminate");
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
I read through the descriptions for shutdown(), awaitTermination, and shutdownNow();
I understand that
shutdown() only stop submitting new threads.
awaitTermination waits for the running threads to be shutdown. Returns a value if one of completed execution, time out or current thread interrupted.
shutdownNow() use Thread.interrupt() to interrupt threads.
My question is, if I know for sure that my threads only use sleep which can be interrupted by Thread.interrupt(). Is there still a value to call awaitTermination like what oracle recommended?
I know that shutdownNow() might have a chance to not shutdown a thread, but why can't we go ahead and do something like this to force stop the threads then see if there are still threads not stoped?
pool.shutdown();
pool.shutdownNow();
try {
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
System.err.println("Pool did not terminate");
}
}