Normally, I let my threads run method end and that is the end of the thread. However, what if my main method is running or waiting in the run method and the thread object itself becomes no longer reachable, and it is a daemon thread. Will this thread end, or will it stay and wait until it is allowed to leave the run method before it ends.
Logically it seems like the thread must wait forever, even if there are no other references to it. This being the case it appears that a running/waiting thread can serve to make some class instances live forever unless the thread is allowed to exit.
Is this true? I could not find good info in jvm spec or JLS about when threads can end. Only info about locks and whatnot...
No running thread is ever unreachable, as a running thread always belongs to a ThreadGroup; this is by design.
While the JVM is up, no thread will ever just die because it is unreachable or for any other reason other than its run() method terminating, either normally (via a return) or abnormally (via an exception.)
It's certainly true that a running yet forgotten thread could be solely responsible for keeping lots of garbage alive.
And at the specification level, JLS 12.6.1: "A reachable object is any object that can be accessed in any potential continuing computation from any live thread." A live thread is always reachable to itself, therefore it cannot be collected. [ July 25, 2006: Message edited by: Jim Yingst ]
Hehe, not quite that. I made a cacheing class that uses weak references. Then I made a thread to clean out the reference queue as objects appear. The net result is that the cacher object stays alive until all of the objects it was holding weakly are gone. I'd rather that object die when i no longer use it. Its really not that bad and will help a bit with diagnostics for it to live until the last of its weak references is cleared.