I am wondering what happen if you declare a local thread within a method? Normally all the local variables will be gone as soon as the function returns since they are all allocated on Stack. However, it seems that a local thread would be a different story. Is that right?
public int A() {
Thread t = new Thread() {
doSomething();
}
t.start();
return -1;
}
A Thread is its own GC root. So any time you create a thread despite its creation context it will not be ready to GC until its run method completes. This is true even if the local method completes and the thread is still alive.
Example:
After
//do somethign else quicklyanything defined that did not escape the method is then marked for GC. Thread th will not be marked for GC and is correctly placed on the heap with it’s own thread-stack.