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;
Whenever we want to stop a thread from running state by calling stop() method of Thread class in Java. This method stops the execution of a running thread and removes it from the waiting threads pool and garbage collected. A thread will also move to the dead state automatically when it reaches the end of its method.
Modern ways to suspend/stop a thread are by using a boolean flag and Thread. interrupt() method. Using a boolean flag: We can define a boolean variable which is used for stopping/killing threads say 'exit'. Whenever we want to stop a thread, the 'exit' variable will be set to true.
just keep the references of your custom threads instead of ID and use Thread. interrupt() to terminate the thread or maintain a Map<String,Thread> for each thread id.
interrupt() method: If any thread is in sleeping or waiting for a state then using the interrupt() method, we can interrupt the execution of that thread by showing InterruptedException. A thread that is in the sleeping or waiting state can be interrupted with the help of the interrupt() method of Thread class.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With