Threads and lifecycle question 5 of 180 junior
What is the difference between a daemon thread and a user thread?
- Daemon threads get a lower priority
- Correct: The JVM exits when only daemon threads are left, and they are not given a chance to finish
- Daemon threads cannot be interrupted
- Daemon threads run in a separate process
The JVM stays alive while at least one non-daemon thread runs. Daemon threads are not counted, so when
the last user thread finishes the JVM exits and daemon threads are stopped where they stand: no
finally blocks, no shutdown of resources.
That makes daemons right for background housekeeping (a cache evictor, a metrics flusher) and wrong
for anything that owns state someone will miss, such as a writer with a buffer that has not been
flushed. setDaemon must be called before start(), otherwise it throws
IllegalThreadStateException.