Can anybody tell me what daemon threads are in Java?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
JVM will accomplish the work when a last non-daemon thread execution is completed. By default, JVM will create a thread as nondaemon but we can make Thread as a daemon with help of method
setDaemon(true)
. A good example of Daemon thread is GC thread which will complete his work as soon as all nondaemon threads are completed.All the above answers are good. Here's a simple little code snippet, to illustrate the difference. Try it with each of the values of true and false in
setDaemon
.For me, daemon thread it's like house keeper for user threads. If all user threads finished , the daemon thread has no job and killed by JVM. I explained it in the YouTube video.
A few more points (Reference: Java Concurrency in Practice)
When all non-daemon threads finish, the JVM halts, and any remaining daemon threads are abandoned:
Due to this reason daemon threads should be used sparingly, and it is dangerous to use them for tasks that might perform any sort of I/O.
Daemon threads die when the creator thread exits.
Non-daemon threads (default) can even live longer than the main thread.
Let's talk only in code with working examples. I like russ's answer above but to remove any doubt I had, I enhanced it a little bit. I ran it twice, once with the worker thread set to deamon true (deamon thread) and another time set it to false (user thread). It confirms that the deamon thread ends when the main thread terminates.