Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

garbage collection query

 
Sneha Kapoor
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



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
Posts: 277
Eclipse IDE Java PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic