Java Thread terminate reference Java Thread terminate reference multithreading multithreading

Java Thread terminate reference


It's an object like any other, isn't it?

No, it's not. It represents a non-memory resource. Would you expect a file to be deleted because an object that represents it is garbage collected?

In fact, when it comes to garbage collection, a Thread object is very much not "like any other" object, because a thread is itself a root of the reachability tree, so any objects referred to by fields (or local variables on the stack) of a Thread object that represents a running thread are by definition not eligible for garbage collection.


The JLS section 12.6 says this:

"A reachable object is any object that can be accessed in any potential continuing computation from any live thread.".

From this we can infer that live threads are implicitly reachable, and won't be garbage collected for as long as they are alive. The existence or otherwise of a reachable reference to the Thread object is not relevant, though (as @Jon Skeet says) a thread does implicitly hold a reference to its own Thread object, so that Thread.currentThread() will work.


For the same reason you can't just set a reference to a JFrame to null to make the window magically disappear. The JVM has a reference to the thread, so even if you forget about the thread, the JVM won't. You'll need to terminate the thread properly, preferably by having its main function end.