Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous object and Garbage Collection in Java

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?

like image 311
skrtbhtngr Avatar asked May 18 '26 14:05

skrtbhtngr


1 Answers

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

like image 102
Prasad Kharkar Avatar answered May 20 '26 03:05

Prasad Kharkar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!