views:

703

answers:

3

If a Thread creates a daemon Thread, can I rely on the fact that when the parent exits the run method, the son will also terminate?

+5  A: 

No - threads are independent. There's no sense of one thread "owning" another and forcing termination.

If you're really asking whether when all the non-daemon threads in the application have died, you can rely on the process dying: yes, you can. But that's all you can rely on.

In particular, if there are two non-daemon threads, each of which has created a daemon thread, and one of the non-daemon threads terminates, then the remaining three threads will continue running.

Jon Skeet
How you can write an answer this complete within one minute of the question's posting is beyond me. Even if you went back and edited it, that's still only two minutes.
Michael Myers
Answer Thief! jk. ;)
John Gietzen
It's only a few sentences. I'm a fairly quick typist and happened to see it early. I think my record is to answer a question and have it accepted before it was a minute old ;)
Jon Skeet
But you spelled "independent" wrong!
Glenn
Doh, fixed thanks :)
Jon Skeet
A: 

From: http://journals.ecs.soton.ac.uk/java/tutorial/java/threads/daemon.html

When the only remaining threads in a process are daemon threads, the interpreter exits. This makes sense because when only daemon threads remain, there is no other thread for which a daemon thread can provide a service.

John Gietzen
+1  A: 

I believe daemon threads are tied to the JVM and not the creating thread.

Gordon