[Before I begin I tried searching related questions, since I found none, I ask a question here]
I am learning Java, and the following scenario hit my head:
class MyThread extends Thread {
void run(){
//a heavy function
}
}
And now in the main thread, I invoke this thread as:
public static void main(...){
new MyThread().start();
System.gc(); //just a request..
//end of main thread too.
//Reference to that MyThread object is now zero.
}
I ran that code. It seems the thread is still alive. The program ends when all the threads quit.
My questions:
otherThread.join()
in main()
?I have a few explanation of myself (but I do not know how right I am -- the reason I made a post here):
this
reference, so the ref count is again not zero.Am I correct in any of the explanations above? Or is there any other explanation altogether?
Thanks and regards :)
Each running thread constitutes a root for the GC. Any object reachable from one of the roots is not eligible for GC, and the thread has a thread-local reference to the java.lang.Thread
instance (returned by Thread.currentThread()
). So no, your thread won't be GCed until it ends running, since the Thread
instance is reachable from the running thread.
I don't see why it would be a bad thing not to call join()
on the spawned thread. If you don't care when the spawned thread ends, you don't need to join it. The application will stop when the last non-daemon thread stops running.
Also, note that the number of references is not what is used by the GC to tell if an object is eligible for GC or not. Graphs of objects which maintain references to each other (a DOM tree for example) can be eligible for GC, if the graph is not reachable anymore.
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