Thread t = new Thread(); t.start(); t = null; now what will happen to the created thread?
One of the replies was that:
As long as it's not dead, it belongs to a ThreadGroup, which keeps it from being collected.
Is it true that a live thread doesn't get collected by GC just because there is a reference from ThreadGroup to it?
I tried to prove it by using this program
Here was the result java -Xmx100m -Xms80m -verbose:gc -cp classes Test Thread started Active thread count2 Active thread count2 Active thread count2 Remove thread from thread group Done [GC 307K->107K(81344K), 0.0015450 secs] [Full GC 107K->107K(81344K), 0.0093870 secs] Active thread count1 Active thread count1 Active thread count1
GC seemed to ignore the live thread even if there was no reference from the thread group to it.
Will it make more sense if the real reason is something like all live threads will be automatically added to GC root set and therefore keep them from being collected even if there was no reachable reference to it?
GC seemed to ignore the live thread even if there was no reference from the thread group to it.
A live thread is more than just a thread object which is stored in some class. There is stack memory allocated to it too. Not to mentioned thread stuff at the OS layer.
You may be able to force the thread object to be dereferenced from the thread group, but you didn't delete the root. A "root" is defined as a starting point to check for reachability. There are many types for roots, and the thread's stack is one of them.