To see the working of finalize()
method in java which is called when the object is about to be destroyed, I have wrote the following program
class counterTest{
public static int count;
public counterTest(){
count++;
}
}
public class finalize {
public static void main(String args[]){
counterTest obj1=new counterTest();
System.out.println("Number of objects :" + counterTest.count);
counterTest obj2=new counterTest();
System.out.println("Number of objects :" + counterTest.count);
Runtime rs=Runtime.getRuntime();
obj1=null;
obj2=null;
rs.gc();
}
protected void finalize(){
System.out.println("Program about to terminate");
counterTest.count--;
System.out.println("Number of objects :" + counterTest.count);
}
}
I expected the output to be like this
Number of objects :1
Number of objects :2
Program about to terminate
Number of objects :1
Program about to terminate
Number of objects :0
But I am just getting the first two lines. Since I am making the objects references to null and then calling the gc()
method, I expect that the statements written in inside finalize()
method should be displayed. Does this mean there is no guarantee that finalize()
method will be called each time we have used gc()
method.