How to shut down all Executors when quitting an application?

concurrency, java

Solution

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.

Problem

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 prevent the JVM from exiting. I.e. System.exit(0) doesn't necessarily work as expected if there are Executors around. It would seem necessary to put some kind of ``` public void stop() { exec.shutdown() } ``` methods to all classes that contain Executors, and then call them when the application is about to terminate. Is this the only way, or is there some kind of shortcut to shut down all the Executors?

Original source