7

Does a thread self-delete and get garbage collected after it runs or does it continue to exist and consume memory even after the run() method is complete?

For example:

Class A{
  public void somemethod()
  {
  while(true)
  new ThreadClass().start();
  }

   public class ThreadClass extends Thread{
        public ThreadClass()
        {}
        @Override
        public void run() {......}
     }
}

I want to clarify whether this thread will be automatically removed from memory, or does it need to be done explicitly.

Tyler Durden
  • 11,156
  • 9
  • 64
  • 126
Aada
  • 1,591
  • 7
  • 30
  • 57
  • 1
    Note that you are encouraged to use `Task`s instead of using Threads directly. Both get garbage collected after they are used, just like any other Java object is really. – Maarten Bodewes May 26 '13 at 20:26
  • @owlstead: you mean AsyncTask? – Rick77 May 26 '13 at 20:33
  • May be a possible duplicate of : http://stackoverflow.com/questions/2423284/java-thread-garbage-collected-or-not – awsome May 26 '13 at 20:34
  • Take it this way: even if it exists, you can't access it (since no reference to it), and for the same reason will be garbage collected after thread completes! :) – mg007 May 26 '13 at 20:34
  • @Rick77 appologies, I meant tasks like in [`FutureTask`](http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/FutureTask.html), together with an executor... – Maarten Bodewes May 26 '13 at 20:49

4 Answers4

9

This will happen automatically i.e. memory will be released automatically once the thread is done with its run method.

user1889970
  • 726
  • 1
  • 8
  • 12
1

Threads only exist until the end of their run method, after that they are made eligible for garbage collection.

If you require a solution where memory is at a premium, you might want to consider an ExecutorService. This will handle the threads for you and allow you to concentrate on the logic rather than handling the threads and the memory.

Lawrence Andrews
  • 440
  • 4
  • 12
0

Threads are automagically garbage collected on completion of the run method, hence you do not have to do it explicitly.

Luke Taylor
  • 9,481
  • 13
  • 41
  • 73
0

Threads will be garbage collected after their run method has completed. The notable exception to this is when you are using the android debugger. The android debugger will prevent garbage collection on objects that it is aware of, which includes threads that have finished running.

Why do threads leak on Android?

Community
  • 1
  • 1
Final Hazard
  • 77
  • 1
  • 7