In above code at line 10 if i keep Test=null output is-> 2 1 i.e two objects are eligible for garbage collection But if at line 10 i dont keep Test as null output is-> 3 2 1 i.e three objects are eligible for garbage collection i am not able to understand what difference it makes if i will keep Test as null or not.
All three objects are not necessarily garbage collected by the System.gc() call. I put a second call to System.gc() into your code and the third object was collected (that is with with t initialized to null). The initialization of t to null really has nothing to do with it. If the JVM exits before the garbage collector finishes (it is a low priority daemon thread) then you will not always see all objects run their finalize methods.
Instead of a second call to System.gc(), you can try calling Thread.sleep(5000). I did that and all three objects got garbage collected. [ August 10, 2006: Message edited by: Barry Gaunt ]
Originally posted by Barry Gaunt: I put a second call to System.gc() into your code and the third object was collected .....
Instead of a second call to System.gc(), you can try calling Thread.sleep(5000). I did that and all three objects got garbage collected.
When the for loop exits, there are three Test objects on the heap, out of which two are unreachable, where as the third one is referred by reference t. In such a case, how come garbage collector collects all three objects? Is the GC smart enough to "understand" that the reference t is not used anywhere further?
If that is the case, then what would be answer for the following question?
[ August 10, 2006: Message edited by: Neelesh Bodas ]
Joined: Aug 03, 2002
I'm not saying that the second call to System.gc() actually caused the third object to be collected. I put in the second call and the object was collected that's all. The third object was also collected when I put the Thread.sleep() in place of the second System.gc() call. The third object cannot get collected until main() exits. Whether you see it get collected or not is a matter of when the JVM actually exits. [ August 10, 2006: Message edited by: Barry Gaunt ]