Search code examples
program-entry-pointshutdownexecutorservice

Why main thread has no shutdown method


When I am running a main thread as in a public static void main method, the thread terminates when the method completes. I don't do anything explicit to shutdown the thread. Why then in case of ExecutorService. we have a shutdown() method? Why cannot we just let the thread(s) managed by ExecutorService run to completion?


Solution

  • The invocation of shutdown method just means that no new tasks will be accepted by the executor. You can give a timeout to the running tasks(to run to completion) submitted to the executor.

    executor.shutdown();
    try {
        //blocks until all tasks have finished or timeout occurs
        executor.awaitTermination(TimeUnit.MICROSECONDS , Long.MAX_VALUE);
    } catch (InterruptedException e) {
      //Take some action at least Thread.currentThread().interrupt();
    }