Is thread garbage collected at the end of the run() method on the thread, or when the function from which it was called ends?
I have no problem or anything else, but I want to avoid memory leaks, etc.
For people who like the 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) { } } } 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() {
In all languages ββthat I know, garbage (if any language is) is collected when the method ends. I assume Java works too. This means that theoretically, the threads I created in someMethod() are not collected until the end of someMethod() . If we assume that the while loop has been running for a very long time, the application will run out of memory and crash.
My question is: is this true? If so, what should I do to avoid this?
source share