Why do we need to use awaitTermination but not just shutdownNow()?

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");
     }
   } 

Answer

The “standard process” just tries to handle the shutdown gracefully, the premise being not to interrupt the threads when it’s not necessary.

First it stops accepting new task submissions and lets the ongoing tasks finish their work. It proceeds to forceful termination only when they don’t finish within the grace period.

Leave a Reply

Your email address will not be published. Required fields are marked *