Shutting down the ExecutorService is graceful when the main thread terminates

In the utility library, I create an ExecutorService

ExecutorService es = Executors.newSingleThreadExecutor();

Then the main thread will send some jobs to this ExecutorService. When the main thread is complete, I would like to disable the ExecutorService so that the application can exit.

The problem is that I can only change the code in the library utility. One option that I have been considering is to use daemon threads. But then he will suddenly stop working before tasks sent to the service can be completed.

+4
source share
2 answers

Use Runtime#addShutdownHook()to add the current work environment to it.

eg.

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

/ .

+5

shutdownHook , .

shutdownHook , JVM , JVM , es.shutDown(), .

, - . . , ( )

   ExecutorService es = Executors.newSingleThreadExecutor( new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setDaemon(true);
            return t;
        }
    });
+3

All Articles