Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shutdown ExecutorService gracefully when main-thread completes

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.

like image 704
Aksel Willgert Avatar asked Jan 11 '23 20:01

Aksel Willgert


1 Answers

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.

like image 148
BalusC Avatar answered Jan 18 '23 22:01

BalusC