How to shut down all Executors when quitting an application?

前端 未结 5 1324
离开以前
离开以前 2021-01-11 23:36

According to Brian Goetz\'s Java Concurrency in Practice JVM can\'t exit until all the (nondaemon) threads have terminated, so failing to shut down an Executor could pre

5条回答
  •  悲&欢浪女
    2021-01-11 23:43

    Decorate the executor with com.google.common.util.concurrent.MoreExecutors#getExitingExecutorService

    @Beta
    public static ExecutorService getExitingExecutorService(ThreadPoolExecutor executor,
                                             long terminationTimeout,
                                             TimeUnit timeUnit)
    

    Converts the given ThreadPoolExecutor into an ExecutorService that exits when the application is complete. It does so by using daemon threads and adding a shutdown hook to wait for their completion.

    This is mainly for fixed thread pools. See Executors.newFixedThreadPool(int).

提交回复
热议问题