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.
This will happen automatically i.e. memory will be released automatically once the thread is done with its run method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With