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
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).
Probably he meant to say JVM can't stop on its own until nondaemon threads are finished. Its like running a simple class from command like java SomeClass and after the execution of main method JVM stops.
System.exit is a JVM termination command, even if daemon threads are running JVM will shutdown.
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!
You can also provide an implementation of ThreadFactory that marks created threads as daemon threads. I prefer a clean shutdown mechanism (with lifecycle methods) but there are cases where you don't need guarantees about the state/completion of uncompleted tasks when this can be appropriate.
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.