I\'m comfortable with the idea of orderly shutdown on threads scheduled with an ExectuorService
; that is to say, calling shutdown
or shutdownNow<
Daemon threads can be useful, and if they weren't terminated abruptly, they wouldn't be so useful IMO.
Presumably we could imagine another type of thread, which are interrupted when no normal threads are running anymore, instead of being abruptly terminated. That may be a little convenient, but if you had to do any clean up at all, it's likely that you wanted to do an orderly clean up. This would limit the convenience of this feature.
On the other hand, if you had tasks that would not need any clean up at shutdown, deamon threads are quite convenient. And you wouldn't want to waste time waiting them to arrive at some specific state or risk a hang up on shutdown etc., because the reason you are using a deamon thread is because you don't need any kind of clean up. It would be a waste of time to execute anything if the app. is shutting down. If you care, then you shouldn't have used deamon threads.
It's no different with deamon thread pools. If that thread pool is doing tasks that do not need any clean up at shutdown, then it would make sense because of the convenience.
From the JCiP book:
Daemon threads should be used sparinglyfew processing activities can be safely abandoned at any time with no cleanup. In particular, it is dangerous to use daemon threads for tasks that might perform any sort of I/O. Daemon threads are best saved for "housekeeping" tasks, such as a background thread that periodically removes expired entries from an in-memory cache
I tend to have different pools for daemon and non-daemon threads. Daemon pools tend to do recurring clean up jobs, monitoring and background tasks which don't matter if one or two is not executed. Any task which is only meaningful while the application is still running is good to make a daemon thread task. e.g. GC threads are daemon threads.
is it bad practice to use daemon threads in a ExecutorService's thread pool?
If the tasks sent to that particular ExecutorService
are ok to be terminated abruptly, then why not, that's what daemon threads do. But generally, there are not many tasks that are ok to be terminated with no shutdown ceremonies at all, so you must know what you're doing if you opt to daemon threads.
finalize()
is called when an object is about to be garbage collected. There are no guarantees on when, if ever, any particular object will be GCd, and ThreadPoolExecutor
is no exception, so its finalize()
may or may not be called. The behavior depends on the particular JRE implementation, and even with the same implementation, may vary from time to time.