"The virtual machine terminates if the last non-daemon thread has finished." My question is, What happens to the daemon threads spawned by the application? Why does the JVM not wait for them to finish?
-
possible duplicate of [when is the main thread stops in java?](http://stackoverflow.com/questions/7416018/when-is-the-main-thread-stops-in-java) – paulsm4 Oct 10 '11 at 07:31
-
2Because that would defeat the "special" nature of daemon threads. .NET more sensibly calls them Foreground threads (non-daemon) and Background threads (daemon), where an active Foreground thread (non-daemon) will keep the VM alive while a Background thread (daemon) will not. – Oct 10 '11 at 07:33
2 Answers
The whole purpose of a daemon thread is that it not not keep the JVM alive if it is the only thread running; this is by design. There are many reasons you might wish to do this.
For example, with a Swing application the user may have invoked a long running task on a background daemon thread (as opposed to on the Event Dispatch thread). Prior to the task completing the user attempts to exit the application. At this stage the application developer may have decided that it is better to shut down the application immediately rather than have the shut-down attempt delayed until the long running computation completes, hence why these decided to assign the computation thread daemon status.

- 54,009
- 15
- 113
- 152
-
But what about "what happens to the daemon thread"? I guess nothing happens. It just stops running... – Ringding Oct 10 '11 at 15:10
-
Do the daemon threads really stop working after the program has stopped execution? I mean this would be like saying that the daemon threads depend on the main thread to exist. Is it really so? – n_g Oct 11 '11 at 06:03
Because they're daemon threads. That's what it means. It doesn't mean anything else.

- 305,947
- 44
- 307
- 483