Need Help to understand Garbage collection Topic - Isolating a Reference - K&B book - SCJP5 - Page 250 - Fig-3.7 After many postponements for preparing for the exam, I am back into studying the book finally. I am in chapter 3 of K&B book. I am stuck at Garbage collection Island references. I really appreciate if somebody can explain how to tackle questions on the exam for this topic. Also if possible can somebody explain the Fig 3.7 (page 250) of the book. I cannot understand how to draw this diagram looking at the code. I mean the arrows and figuring out how they become unreachable. Please help me understand.
I really appreciate your time. Thanks in advance.
Now the memory representation of this code will look like this
So you can see that there is a reference (p) pointing to the object in the heap. Now if I set p to null i.e. p = null, then this reference will be removed and thus the two objects will be eligible for garbage collection. Now lets add a little twist to the code
Now the memory map of this code will look like
Here the pet field in Person class points to the Dog object and the owner field in the Dog class, points to the same Person class object. But still there is only one reference in the stack which points to these two objects, so again if the reference p is set to null, then these two objects will be eligible for garbage collection. And these two objects pointing to each other with no reference in the stack pointing to them are called to be on an island of isolation as they are isolated...
Thanks for your help and time. I revisited the topic in K&B - Isolating a Reference. I drew the memory diagram and it makes sense now.
Joined: Oct 11, 2006
Ankit, it looks like you are good at drawing memory representation diagrams. Can you please tell how can I get used to these diagrams because every question related to GC is confusing me more and more though I feel like I got it in the beginning. I understood that I have to have the reference variable point to the object(box) and put the instance variable in the object(Box).
But then how do you join objects(Boxes) with arrows and delete them? Thanks in advance and I really appreciate your time. Please reply.
Esther Kak wrote:But then how do you join objects(Boxes) with arrows and delete them?
I delete arrows using the backspace key (I hope the joke's funny)
Anyways, when a reference variable starts pointing to another object or to null, then the reference stops pointing to the new object and thus the arrow between the earlier object and the reference is gone.
Lets take an example
At line 1, the reference p is pointing to the first Person object.
But at the next statement, p starts pointing to a different object, so the first one is eligible for GC