Search code examples
javamultithreadingthread-safetyterminate

What happens to the "thread of the object" extending Thread, if the object is no longer referred to?


public class MyClass extends Thread{
    public void run() {

       try {
          while(!Thread.currentThread().isInterrupted()) {
             // ...
          }
       } catch (InterruptedException consumed)
          /* Allow thread to exit */
       }

    }
    public void cancel() { interrupt(); }

    //etc.
}

Should I always call cancel() like this before deconstructing the object for some reason, or should I not worry about it?


Solution

  • A running thread, and its corresponding Thread object, is a GC root. It is therefore ineligible for garbage collection.

    If you want to GC the Thread object of a running thread, that thread will need to stop. If you've correctly implemented an interruption mechanism, you'll need to interrupt your thread with your cancel() method. Once the thread returns from its run() method, it completes and is no longer a GC root. If you then have no more live references to its Thread object, it will be garbage collected.