javajava.util.concurrent

Difference between shutdown and shutdownNow of Executor Service


I want to know the basic difference between shutdown() and shutdownNow() for shutting down the Executor Service?

As far as I understood:

shutdown() should be used for graceful shutdown which means all tasks that were running and queued for processing but not started should be allowed to complete

shutdownNow() does an abrupt shut down meaning that some unfinished tasks are cancelled and unstarted tasks are also cancelled. Is there anything else which is implicit/explicit that I am missing?

P.S: I found another question on How to shutdown an executor service related to this but not exactly what I want to know.


Solution

  • In summary, you can think of it that way:

    You can try the example below and replace shutdown by shutdownNow to better understand the different paths of execution:

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(1);
        executor.submit(new Runnable() {
    
            @Override
            public void run() {
                while (true) {
                    if (Thread.currentThread().isInterrupted()) {
                        System.out.println("interrupted");
                        break;
                    }
                }
            }
        });
    
        executor.shutdown();
        if (!executor.awaitTermination(100, TimeUnit.MICROSECONDS)) {
            System.out.println("Still waiting after 100ms: calling System.exit(0)...");
            System.exit(0);
        }
        System.out.println("Exiting normally...");
    }