How to shut down all Executors when quitting an application?

前端 未结 5 1352
离开以前
离开以前 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:54

    By default, an Executor will create only non-daemon threads. You can override that by supplying the Executor with your own ThreadFactory. Here's an example:

    class DaemonThreadFactory implements ThreadFactory {
      public Thread newThread(Runnable r) {
        Thread t = new Thread(r);
        t.setDaemon(true);
        return t;
      }
    }
    

    Be cautious, though, because the JVM will exit right away even if these threads are busy doing useful work!

提交回复
热议问题