At what point is only a single object eligible for GC? A. After line 8 runs. B. After line 9 runs. C. After line 10 runs. D. After line 11 runs. E. Compilation fails. F. Never in this program. G. An exception is thrown at runtime. Answer: G is correct. An error at line 10 causes a NullPointerException to be thrown because e2 was set to null in line 8. If line 10 was moved between lines 7 and 8, then F would be correct, because until the last reference is nulled none of the objects is eligible, and once the last reference is nulled, all three are eligible.
My question is if I remove line number 10 from the code will the answer to this question will be choice A.I mean if there was supposed to be no runtime error after removing line number 10 from the above code then the answer to the question 'At what point is only a single object eligible for GC?' would be A.
I claim that after line 8 is executed, the references e1 and e3 are still alive. In addition e3.e is a reference to e2. Therefore, all three objects that were created are still alive and cannot be garbage collected.
But after line 8 the reference e3.e is on the heap and not on stack(because e is an instance variable of e3) and e2 has no contact will the external world although it has an active reference e3.e so it is eligible for GC.
Lets say you comment out line 10 (and that no exception is thrown at runtime), then after the statement on line 11 has executed, then one object will be eligible for GC from the heap, that being the object that was referenced by e1.
I find that it always helps to depict the scenario by drawing out the objects that would be on the heap. It does help! Especially in the exam Best regards [ July 16, 2008: Message edited by: Keith Nagle ]
Originally posted by rakhee gupta: Why not objects referenced by e2 and e3 along with e3 are eligible for GC after line 3 after all their references(e2,e3) also being set to null?
Again, forgetting about the NPE, Objects referenced by e2 and e3 are not eligible for GC as they are still accessible by any live thread via references e1.e and e3.e You have to try and visualize it! Best regards.
a bit of art, as a gift, the permaculture playing cards