Rajiv and Manish,
I'm still working out garbage collection and so forth, so this question intrigued me.
Manish's explantion is good, but misses a few points.
ref var i2 ===> null (i2 no more points to memory area A and B & eligible for GC)
ref var i3 ===> null (i3 no more points to memory area B and C & eligible for GC)
After i2=null is executed, A.i will still reference B.
Likewise, after i3=null B.i ==> C and after i4=null C.i ==> A
Yes, the references
i2, i3 and i4 are pointing to null, but the objects
A, B and C still reference each other.
As such, it would seem that they are not eligible for gc, however; they have no external reference (creating an 'island of isolation'), they are unreachable and therefore eligible for gc.
But the question remains: is setting each reference to null neccessary
for the three objects to be eligible for gc?
My answer: No. To become eligible for gc, an object needs to become unreachable. How that happens is somewhat irrelevant, what's important is that the object no longer has any external references.
Consider the following modified code:
from the output, we can surmise that i wasn't eligible for gc at the time of the explicit System.gc call at line 3, but i2, i3 and i4 were. i will be eligible for gc after line 4, but the program doesn't last long enough for the message to print.
It is instructive to note that if m1 is modified to return an Island and returns i2, i3 or i4, and line 2 is altered to i = i.m1();, then only the object initially referenced by i will be gc'd at line 3
Hope that helps,