How to shut down all Executors when quitting an application?

前端 未结 5 1362
离开以前
离开以前 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-12 00:04

    There's no shortcut to do them all, no. Also, you should probably call shutdownNow() rather than shutdown(), otherwise you could be waiting a while.

    What you could do, I suppose, is when you create the Executor, register it in a central place. Then, when shutting down, just call shutdown() on that central object, which in turn could terminate each of the registered executors.

    If you use Spring, then you can take advantage of its factory beans which create and manage the Executors for you. That includes shutting them down gracefully when the application quits, and saves you having to manage them yourself.

提交回复
热议问题