14.4. Daemon Threads¶
In Java, every Thread object has a boolean
property named
daemon that impacts when a program can exit – its value can be
accessed using isDaemon(). Under normal circumstances, a Java program
will only exit under two conditions:
explicit exit: the exit(int) method in the Runtime class is called (e.g., as is done by System.exit(int)); or
implicit exit: all the threads currently running are daemon threads (i.e., they have their daemon property set to
true
).
Thread Type |
Prevent implicit exit? |
|
---|---|---|
non-daemon |
|
|
daemon |
|
|
A thread’s daemon property cannot be changed after the thread has started executing (i.e., after it’s start() method has been called). When a new thread is created, its daemon property is set to the same value as the thread that created it.
The main thread is a non-daemon thread, so any new threads that are created in the main thread will also be non-daemon threads, i.e., unless their daemon value is changed to true using using setDaemon(boolean) before they are started.