Is a thread garbage collected when the run()
method within the thread is finished or when the function where it was called from finishes?
I don't have an issue or anything, but I want to avoid memory leaks and such.
For people who like code:
public void SomeClass {
public SomeClass() {
}
public void someMethod() {
Object data = veryBigObject;
while(true) {
MyThread thread = new MyThread(veryBigObject);
thread.run();
try {
Thread.sleep(1000);
} catch (InterruptedException e) { /* do nothing */ }
}
}
public static void main(String[] args) {
SomeClass myclass = SomeClass();
myclass.someMethod();
}
}
public class MyThread extends Thread {
private Object data;
public Thread(Object data) {
this.data = data;
}
public void run() {
// do stuff with data
}
}
In all languages I know, garbage (if the language has any) is collected when a method ends. I assume Java does as well. That means that theoretically the threads I create in someMethod()
are not collected until someMethod()
ends. If we assume the while loop runs for a very long time, the application would run out of memory and crash.
My question: is this true? If so, what to do to avoid it?