Question

My question is: When is an anonymous object swept by the garbage collector in Java?

The code is:

class Test extends Thread
{
    Test(){}
    public void run()
    {
        for(int i=0;i<4;i++)
            System.out.println(this.getName()+"i="+i);
    }
    protected void finalize()
    {
        System.out.println("Finalized");
    }
    public static void main(String args[])
    {
        new Test().start();
    }
}

From what I know about Java, any unreferenced object is swept by the GC. But there is no object reference here. Although the garbage collection process cannot be predetermined, but, still, when would the GC be "probably" done?

Was it helpful?

Solution

An object is eligible for garbage collection when there are no references to it and any live thread is not accessing it. When to garbage collect it depends on JVM

OTHER TIPS

Actually garbage collection will remove any objects that not reachable from the stack (= all active function calls in all threads).

When you call start() you are creating a new thread and java will call run() for you. In created this thread, the reference to your Test object is copied to the stack of the new thread. And by calling your run() is on the stack of the new thread.

When your run() function is done, the thread will be removed. And the Test object will be no longer referenced, and can be cleaned up. (in java you normally speak about eligible for cleanup, so you say: it is possible that it will be cleaned, but as always the garbage collection decides if/when it really happens.

Actually garbage collector will pick up objects when they are not accessible by any live threads. So in your case object you created will be up for GC as soon as thread exits main method.

Imho the answer is still: It cannot be said. However, in this case in can only be removed by the GC after the thread finished its work. The actual "finalization" time depends on some more factors.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top