as per Java Doc, The finalize method is never invoked more than once by a Java virtual machine for any given object.
i'm trying to call finalize on an object which is newly created and holds reference.
// Java program to demonstrate requesting
// JVM to run Garbage Collector
public class Test
{
public static void main(String[] args) throws InterruptedException,Throwable
{
Test t1 = new Test();
Test t2 = new Test();
t1.finalize();
t1.finalize();
// Nullifying the reference variable
t1 = null;
// requesting JVM for running Garbage Collector
System.gc();
// Nullifying the reference variable
t2 = null;
// requesting JVM for running Garbage Collector
Runtime.getRuntime().gc();
}
@Override
// finalize method is called on object once
// before garbage collecting it
protected void finalize() throws Throwable
{
System.out.println("Garbage collector called");
System.out.println("Object garbage collected : " + this);
}
}
output is : something like below :
Garbage collector called
Object garbage collected : Test@232204a1
Garbage collector called
Object garbage collected : Test@232204a1
Garbage collector called
Object garbage collected : Test@232204a1
Garbage collector called
Object garbage collected : Test@6fffd0ea
I can't understand the behaviour of GC how its working, and what is happening if i'm calling finalize() method.