Hello, I am studying for the 1ZO-851 and am confused on a GC question. Please note the following code below:
The question asks how many objects are available for GC after the "base = null; f1 = null; f2 = null;" line. The (supposed) answer is zero. I understand that the Fiji object created in Main can be reffered to by "this". However, the book says that other two objects (created in go()) can be referred to by f3 and f3.f. I can only see that the second object is referred to by f3. Am I missing something or is this answer wrong?
Pencil, paper and eraser. That is what you need. Draw some squares, label them base, f1, f2 and f3. Draw a second square next to each, labelled base.f, f1.f, f2.f and f3.f.
Go through the code line by line, and for each object you see, write a number on the paper. Now draw arrows from the references to the numbers. Whenever you reassign anything, draw an arrow from the reference to that object, and whenever you set anything to null, remove the arrow from that reference. You will end up with something rather like this:This shows there is (at present) a series of references from f4 to no 6. As long as you still have a reference to f4, no 6 is still accessible and is not eligible for GC.
You will find that every object created in your class is still accessible at the end of the go() method.
Joined: Jul 29, 2011
Thanks for the response. I think, however, that your code block got garbled.
What might be confusing is that a Fiji object also has a Fiji member within it.
Line 12 creates a Fiji instance, and f1 points to it. Let's call it Fiji Instance 1.
Line 13 sets the static "base" is set to point to Fiji instance 1 as well.
Line 14 creates a Fiji instance, and f2 points to it. We'll call it Fiji Instance 2.
Line 15 sets f1.f to point to Fiji Instance 2.
Line 16 sets f3 to point to f1.f. thus pointing to Fiji Instance 2.
Line 17 sets f2.f to point to f1, thus pointing to Fiji Instance 1.
Note that as a result of all this, f3 is pointing to Fiji Instance 2, and f3.f is pointing to Fiji Instance 1. In effect, if line 16 was rewritten to say "Fiji f3 = f2" it would do EXACTLY the same as the code as written in your example.
Line 18 throws out the base, f1, and f2 references. However, f3 still exists. It's pointing to Fiji Instance 2. Since Fiji Instance 2's "f" member is pointing to Fiji Instance 1, and f3 is keeping the references live, there are 2 Fiji objects that must remain in existence, and cannot be garbage-collected.
This is one of those things, though, that's visualized more easily with pen and paper... I hope my explanation clarifies somewhat rather than muddying the water.
Joined: Oct 13, 2005
Jim Follen wrote:Thanks for the response. I think, however, that your code block got garbled.
No, I hit "submit" by mistake instead of "preview". I have completed it since then.
Joined: Jul 29, 2011
Thanks to you both for your help. It is clear to me now.