Monday, April 25, 2011

Relation between Parent and Child thread in java


It is  possible that a parent thread dies before the child ones?
Explanation:
Say i have a Thread "Parent" in it i am starting another two threads say "child1" and "child2" then both childs are still in running phase and Parent Thread dies.
Ans:

All Threads are 'unrelated', there are no parent and child threads. So once the 'parent' thread kicks off 'child1' and 'child2', then the three threads are independent. They can end in any order and they don't affect the running of other threads. Which means 'parent' can die before 'child1' and 'child2'.

There are some modifications to this. For example, if 'parent' is the last non-daemon thread running (and thus 'child1' and child2' threads are daemon threads), then when 'parent' dies, the JVM starts to shutdown, so the 'child' threads would also die. The last modification would be if you have some synchronizing code that prevents 'parent' from dieing until the 'child' threads die, or that signals the 'child' threads to die when the 'parent' does.

1 comment: