Hi all, will daemon thread stop working when the enclosing it thread will finish? Or daemon thread will stop when the \"main\" thread will finish?
I tested this example
Hi all, will daemon thread stop working when the enclosing it thread will finish? Or daemon thread will stop when the "main" thread will finish?
A daemon thread will be stopped by the JVM when the main execution thread and all the user threads terminated their execution. Then, your daemon thread is strictly dependent from the execution of the user threads and the main thread of your program.
Instead, the JVM will shutdown your program until all the user threads have been terminated.
As recap, the user thread is a thread that keeps a program from quitting, because, even if the main thread of your program is terminated, the JVM doesn't stop your program until all the user threads have completed the requested job. Only when all the user threads have terminated, the JVM can shutdown the program.
Then, a daemon thread is a thread that doesn't keep your program from quitting. For other info, check this old question of SO.
Check the Thread API. The documentation for setDaemon()
method reports below:
Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon thread.
Or the Runtime API:
The Java virtual machine shuts down in response to two kinds of events:
1) The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or
2) The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.