• Post Reply Bookmark Topic Watch Topic
  • New Topic

Garbage Collection: OCA Java SE 7: Ch3, P218, #11  RSS feed

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java OCA question : Garbage Collection
Given:

When "do stuff" is reached, how many objects will be eligible for garbage collection?
A. 0
B. 1
C. 2
D. 3
E. 4
F. 5
Correct answer is B. 1. 
Book explanation:
It should be clear that there is still a reference to the object referred to by a2, and that there is still a reference to the object referred to by a2.b2.  What might be less clear is that you can still access the other Beta object through the static variable a2.b1 --- because it's static.

My thought process:
a1 = null; makes a1 eligible for GC.
           also makes a1.b1 and a1.b2 unreachable, and eligible for GC.
b1 = null; makes b1 (in main) eligible for GC.
b2 = null; makes b2 (in main) eligible for GC.
So to my mind, the answer should've been F. 5. 
In regards to the book explanation... the book explanation is only talking about a2... It doesn't mention the fact that a1 has been made null and unreachable... and b1(in main) has been made null and unreachable... a2 (it seems) cannot reach either of these... so the answer should be at least 2 objects eligible for GC. 

Where am I going wrong in my thinking?  What is a better way to approach how the GC works?

Book Reference:
OCA/OCP Java SE 7
Programmer I & II Study Guide
Kathy Sierra & Bert Bates
Chapter 3: P. 218, #11
 
author & internet detective
Marshal
Posts: 37518
554
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Winston Bodega wrote:a1 = null; makes a1 eligible for GC.
           also makes a1.b1 and a1.b2 unreachable, and eligible for GC.

No. An object is only available for GC when nothing is pointing to it. Remember that a1 is a reference to an Alpha object.

Pretend I give you a pen and tell you to point to it with your right and left thumbs. Then I tell you to stop pointing with your right thumb. That's what a1=null is doing. However, your left thumb is still pointing at the pen so it can't be garbage collected.
 
Winston Bodega
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jeanne,
Thank you, that helps me understand it a little bit better. 
I guess the better question I should've asked is --- Which object is eligible for garbage collection here? 
Is it the Alpha object referenced by a1? 
Or is it the Beta object referenced by b1?
Or neither?

 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37518
554
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's the Alpha object referenced by a1. Try drawing it out; you'll see no references to a1 remain.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!