This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I thought the answer would be zero as at LINE1 and LINE2 the other() method assigns the 'z' reference of each object to the objects referred to by c1 and c2. So the original objects of c1 and c2 are being refered to by its 'z' variable
However the answer given was that the two objects referred to by c1 and c2 are eligble for garbage collection even thought the have references to each other
Can anyone please explain why they are eligible for garbage collection?
Assuming the following is the corrected code that you want an answer to:
At the point when you make c2 = null; you have lost any reachable reference to the objects c1 and c2 even though they are being referenced from within c1.z and c2.z. This is a classical case of circular reference leading to "islands of isolation". The garbage collector is intelligent enough to realize that these two objects cannot be accessed by any program from the outside world. Hence the two objects will be garbage collected. On uncommenting the call to System.gc(); you may see the finalize() method being called twice and printing (it did in my case):
Joined: Jun 10, 2008
Well you posted the correct code while i was writing the modified code
Anyways, the answer is the same. Here your actual reference variables c1 and c2 are no more pointing to the actual objects but are pointing to a third object referenced by c3. It has the same effect as setting c1 = c2 = null; The rest of the explanation is the same.