title: Java threads and garbage collector
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/2423284/java-thread-garbage-collected-or-not">Java Thread Garbage collected or not</a>  </p>
  </blockquote>
  
  
  
  <p>Consider the following class:</p>
  
  <pre><code>class Foo implements Runnable {
  
    public Foo () {
         Thread th = new Thread (this);
         th.start();
    }
  
    public run() {
      ... // long task
    }
  
  }
  </code></pre>
  
  <p>If we create several instances of <code>Foo</code> by doing</p>
  
  <pre><code>new Foo();
  new Foo();
  new Foo();
  new Foo();
  </code></pre>
  
  <p>(note that we don't keep a pointer to them).</p>
  
  <ol>
  <li><p>Could those instances be removed by the garbage collector <em>before</em>
  the thread in <code>run()</code> ends? (In other words: is there any reference
  to the <code>Foo</code> objects?)</p></li>
  <li><p>And, in the other hand, will those instances be removed by the GC
  after the thread in `run()' ends, or are we wasting memory ("memory leak")?</p></li>
  <li><p>If either 1. or 2. are a problem, what's the right way to do it?</p></li>
  </ol>
  
  <p>Thanks</p>