I was trying to understand the behavior of GC and I found something that interests me which I am unable to understand.
Please see the code and output:
public class GCTest {
private static int i=0;
@Override
protected void finalize() throws Throwable {
i++; //counting garbage collected objects
}
public static void main(String[] args) {
GCTest holdLastObject; //If I assign null here then no of eligible objects are 9 otherwise 10.
for (int i = 0; i < 10; i++) {
holdLastObject=new GCTest();
}
System.gc(); //requesting GC
//sleeping for a while to run after GC.
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
// final output
System.out.println("`Total no of object garbage collected=`"+i);
}
}
In above example if I assign holdLastObject to null then I get Total no of object garbage collected=9. If I do not, I get 10.
Can someone explain it? I am unable to find the correct reason.