Originally posted by Mohammed EL-Adawi: My answer is after line 9 excutes, because the the third constructed object is no more reachable
After line 9, e3 is set to null. However, the objected that was pointed to by e3, is still referenced by e1.e because of line 7.
But the exam answer is "Never in this program", it was explained that 3rd object is still "has-a" ref to another object which is still alive.
I still have a doubt, because it does not make a sense to have a useless object in the heap, even if 3rd object is still "has-a" ref to another alive object, because that ref also is not reachable.
Partially correct. A circularly referenced island of objects that you seem to suggest can indeed be garbage collected. However, in this case, object pointed to by e1 is not eligible for GC (at line 9) because e1 is still in scope and is not set to null (as yet). So the object pointed to by e1 is referenceable and so is e1.e, and so is e1.e.e, and so on.
Everything on the right side (the objects on the heap) that isn't connected to the left side (your references) at a certain point is eligible for GC. Since all objects on the heap are connected to each other, ALL connections to the references must be cut (by assigning them to null)
6. e3.e = e2;//the green arrowes in the picture 7. e1.e = e3; 8. e2.e = e1; // here all objects are connected to each other, and as long as there is still a way to access them (via a reference on the left side) they wont be garbage collected. Note the connection must not be directely, if there is a path to the object via the other objects on the heap then this is also good and the object is not eligible for GC.
9. e3 = null;// the blue crosses 10. e2 = null; 11. e1 = null; // only here all connections are cut and the island of three objects can never be accessed anymore, so the GC will detect that. Hope this clarifies...