Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Thread terminate reference

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;

like image 239
bline Avatar asked Apr 23 '11 08:04

bline


People also ask

How do you terminate a thread in Java?

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.

How do I stop a particular thread?

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.

How do I stop thread ID thread?

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.

How do you stop a thread from another thread in Java?

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.


2 Answers

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.

like image 130
Michael Borgwardt Avatar answered Sep 30 '22 14:09

Michael Borgwardt


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.

like image 45
Stephen C Avatar answered Sep 30 '22 13:09

Stephen C