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

Does the thread itself create the removal and collection of garbage after it is launched, or does it continue to exist and consumes memory even after the run() method completes?

For instance:

 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 deleted from memory or should it be executed explicitly.

+6
source share
4 answers

This will happen automatically, i.e. the memory will be released automatically after the thread is executed using its start method.

+8
source

Threads exist only until the end of their startup method, after which they become available for garbage collection.

If you need a solution in which premium memory is available, you can consider the ExecutorService . This will process the threads for you and allow you to focus on logic, rather than processing threads and memory.

+1
source

Streams are automatically garbage collected at the end of the run method, so you do not need to do this explicitly.

0
source

Threads will collect garbage after completing their start method. A notable exception is the use of the android debugger. The Android debugger will prevent garbage collection on objects that it knows about, including threads that have finished working.

Why stream leak on Android?

0
source

Source: https://habr.com/ru/post/945891/


All Articles