Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 211
Aada Avatar asked May 26 '13 20:05

Aada


2 Answers

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

like image 148
user1889970 Avatar answered Oct 17 '22 13:10

user1889970


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.

like image 41
Lawrence Andrews Avatar answered Oct 17 '22 12:10

Lawrence Andrews