0
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?

Ryan Marv
  • 109
  • 6
  • 4
    Define _deconstructing_. – Sotirios Delimanolis Aug 30 '14 at 08:48
  • If a thread is running, it's reachable by the GC. I don't understand what question you're trying to ask. – tmyklebu Aug 30 '14 at 08:50
  • Deconstructing: Getting rid of the object's references... – Ryan Marv Aug 30 '14 at 08:51
  • Objects don't automatically destruct when all the references go away. The GC will eventually get around to it. But... if the thread is still running, there's still an implicit reference to your object. It won't automatically stop or get garbage collected just because you aren't referencing it. – selbie Aug 30 '14 at 08:54
  • You shouldn't care about such things, all you need to care about is to define what your thread should do and how long it should do it. So think about if your thread should be externally aborted or not and implement it as needed. Everything else is up to Java. – Thorsten Schöning Aug 30 '14 at 08:54
  • So its thread just keeps it implicitly referenced, thanks, this was my concern. – Ryan Marv Aug 30 '14 at 09:00

1 Answers1

3

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.

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724