Shutdown ExecutorService gracefully when main-thread completes

executorservice, java, threadpool

Solution

Use `Runtime#addShutdownHook()` to add a shutdown hook to the current runtime.

E.g.

Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() {
        es.shutdown();
        try {
            es.awaitTermination(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            logger.info("during await",e);
        }
    }
});

Do this upon construction/initialization of your utility class.

Problem

In a utility library i am creating a ExecutorService ``` ExecutorService es = Executors.newSingleThreadExecutor(); ``` The main thread will then post some tasks to this ExecutorService. When the main-thread completes i would like to shutdown the ExecutorService to allow the application to exit. Problem is i can only change the code in the utility-library. One option I considered was to use daemon-threads. But then it will abruptly shutdown before the tasks posted to the service can complete.

Original source