Aada
Aada

Reputation: 1640

Do threads get automatically garbage collected after run() method exits in Java?

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.

Upvotes: 7

Views: 2987

Answers (4)

Final Hazard
Final Hazard

Reputation: 77

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?

Upvotes: 0

Luke Taylor
Luke Taylor

Reputation: 9599

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

Upvotes: 0

Lawrence Andrews
Lawrence Andrews

Reputation: 440

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.

Upvotes: 1

user1889970
user1889970

Reputation: 736

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

Upvotes: 9

Related Questions