wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes garbage collection query Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "garbage collection query" Watch "garbage collection query" New topic
Author

garbage collection query

Sneha Kapoor
Ranch Hand

Joined: Jun 08, 2009
Posts: 49


At the point that line 12 is reached, how many objects are eligible for garbage collection?


I thought that 2 objects are eligble but answer is 1

Source : Apress SCJP Book
Yogesh Bali
Greenhorn

Joined: May 29, 2009
Posts: 21



yes its correct the answer is one .... the object created by r1 only is eligible for gc..
3 objects created by r1, r2 and r3.. let for our convenience say the object created by r1 is A, object created by r2 is B and object created by r3 is C..
till line 7, what we have is


object A having only one reference -- r1
object B having 3 references -- r2, r4, and r5
object C having only one reference -- r3.


now by line 8, r2=null, means for object B now we are having 2 references only -- r4 & r5. Also our r2 now contains null, not refering to anything else.


by line 9, r4=r2 implies r4 also containing null, so our object B now having only one reference r5.


by line 10, r1=r5 implies our r1 which is refering to object A is now refering to object B.. because r5 points to object B.


and r1 was the only reference to object A, so no one is pointing to object A by now...
object B is referred by r1 and r5...
object C is referred by r3...

So only 1 object eligible for gc..

Java is Easy.. Enjoy studying it
Have a good time : )
Michael Angstadt
Ranch Hand

Joined: Jun 17, 2009
Posts: 274


Try this. Draw an empty square whenever a new instance of an object is created. Put the names of the references that point to that object inside the square. Cross out a reference if it is set to null or assigned to a different object. Any boxes that are empty at the end are eligible for garbage collection:



One box (the left box) is empty, so one object can be garbage collected.

SCJP 6 || SCWCD 5
 
 
subject: garbage collection query