Recently I was asked a question:
We\'ve got the
setPriority()
method to set a thread for low priority. Then why do we need a daemon thr
We've got the setPriority() method to set a thread for low priority. Then why do we need a daemon thread. What's the difference between them?
Typically, daemon threads have nothing to do with priority. The JVM shuts down when all user non-daemon threads finish. Marking a thread as a daemon thread means that it can be safely killed when the JVM exits.
Priority is about scheduling – about how often a thread gets a time slice in comparison to other threads that are ready to run. You can have low priority daemon threads or high priority daemon threads. You can have non-daemon threads that are also low and high priority. As an aside, thread priorities only apply in certain specific situations and on certainly architectures and as a Java thread expert, I never use them.
The concepts are orthogonal (mutually independent) – at least in the Java thread model.
In terms of when to make a thread daemon, I use daemon threads for any tasks that I don't care if they are interrupted when the JVM quits: keep-alive threads, statistics processors, log handling, etc.. Everything mission critical to the application is a non-daemon thread that has to be specifically interrupted or signaled to quit somehow.