Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Multithreading: Behaviour when Reference count of thread object becomes zero

[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:

  • When the reference count is zero, wont the thread be eligible for GC? If it is really eligible, what is the behaviour of garbage collection? Will the thread be terminated?
  • I know its a bad thing to do but is it well defined to not have 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):

  • JVM maitains a reference to the thread as long as it is active. So ref count is never really zero.
  • The executing function has an implicit 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 :)

like image 894
UltraInstinct Avatar asked Nov 30 '22 23:11

UltraInstinct


1 Answers

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.

like image 123
JB Nizet Avatar answered May 02 '23 15:05

JB Nizet