Reputation: 227
Why is it not possible to terminate a thread by setting it's reference to null and letting the garbage collector removing it? It's an object like any other, isn't it?
example:
Thread t = new Thread(new Runnable() {
public void run() {
//...
}
}).start;
t = null;
Upvotes: 6
Views: 1540
Reputation: 719239
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.
Upvotes: 2
Reputation: 346377
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.
Upvotes: 3
Reputation: 1502106
You're only setting a variable's value to null.
So, the question is whether any thread effectively has a reference to that Thread
object. Consider the new thread itself... it could easily include
System.out.println(Thread.currentThread());
What would you expect that to do if the Thread
object had been garbage collected?
Objects are only garbage collected at some point after there are no live references to them any more. Any live thread has a reference to itself.
Frankly, it would be a pain if you had to ensure that you did keep a reference a thread you've just started, in order to prevent it from being stopped abruptly.
Upvotes: 2
Reputation: 77752
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.
Upvotes: 2