An object becomes eligible for GC when it has no live references. That means It cannot be in anyway accessed by a variable still on stack.
The objects may have references but no live reference. For example:
In this example you have 3 reference variables on stack namely a1, a2 and a3.
each refering to an object of type A on Heap. Each object has a reference variable 'a' which is also on Heap. And as you can see 'a' of each object refer to the next object making a cycle and then the references on stack are made to point to null, now all three objects refered by a1,a2 and a3 have no refernce on stack but they refer to each other forming an Island of isolation.
So all these 3 are eligible for gc.As no variable on stack can reach them.
Now lets change the code a little bit:
Now what happens, objects refered by a2 and a3 have no live reference on stack but a1 has.
here you can see a1.a has a variable on stack that can reach it, a1.a points to a2 that means a1.a can reach a2.a and hence a2.a can be accessed by variable a1 on stack similarly a3.a can be reached by a2.a and hence has a live reference. So, In this case none of the object is eligible for GC as each of them have a live reference directly or indirectly.
Hope you get it now.
Please ask if you need further clarification.
binnu yadav wrote:In the first snippet....I was unable to understand line no 7,8,9.
In line 7 While solving this from where do we start i.e. from right side towards left or vice versa ?
In this line of code what happens is as follows:
gb1 variable is created on stack and a new Garb object on heap which will be refered by gb1. It has an instance variable 'g' which gets reference to object passed to the constructor. So when we pass a new Garb object to constructor again a new object is created on heap and gb1.g will refer to it. Now the constructor of the second object created again has new Garb object so, a third Garb object is created on heap and gb1.g.g will refer to it. Now constructor of the third object created has a null in it so now gb1.g.g.g has a null reference.
So you can see we move from left to right creating objects one by one.
What made you think of moving right to left as it makes no sense. How will you create an object when the reference variable its meant for does not exist.