I have a question regarding garbage collection. This question is on ExamLab's Diagnostic Exam and I don't know why the actual answer is given.
How many objects are eligible for garbage collection after executing c.aob = null; ?
Options are 0,1,2,3,4,5 and 'Cannot determine'. Correct answer is 2 and the explanation is 'Draw a diagram'. I have made my diagram and I still think just 1 object is eligible for GC. Can anyone please explain to me why 2 objects are eligible for GC?
Luis Centeno wrote:
Correct answer is 2 and the explanation is 'Draw a diagram'. I have made my diagram and I still think just 1 object is eligible for GC. Can anyone please explain to me why 2 objects are eligible for GC?
It would help if you describe us what you drew. We can't tell you where you went wrong if you don't tell what your did.
However, I am willing to bet that you missed the object that became eligible at line 10.
Thanks for answering, below is the diagram I did...(this is probably the worst diagram ever made, but I made it using paint ) this is how I understand gc. I cannot see how an object becomes eligible at line 10. As far as I understand, only object 3 (blue marked) becomes eligible. Could you please explain what did I do wrong?
It seems like I was missing the d assignment since I didn't see that d references the same object as new A().aob. Thank you so much, I get it now...If I am not wrong, the final diagram would be like this...
This makes eligible for gc to objects 3 and 4, I think...
The only problem here is this above piece in the code. I also got confused about it. Well Say the last object is created and the bit representing it is stored in new A().aob and those bits are transfered to d So d refers to new A().
[ SCJP 6.0 - 90% ] , JSP, Servlets and Learning EJB.
Try out the programs using a TextEditor. Textpad - Java 6 api
Hi Luis. I was under the impression that one object is eligible for GC. I think the key is resolving the Right hand side first and then assigning the reference to that. Since nothing is pointing to new A().aob, from the stack, the object becomes unreachable and hence ready for GC. This is a good question.
Yes still 2 objects will be eligible for gc, as
c=b;//Here c will point to same object as b,
and hence object which was pointed by c prior to above line will be eligible for gc.
and as you said,Object pointed by c.aob will not be available for gc.