Forums Register Login

garbage collection query

+Pie Number of slices to send: Send


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
+Pie Number of slices to send: Send



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 : )
+Pie Number of slices to send: Send

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.
Hey! You're stepping on my hand! Help me tiny ad!
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 1028 times.
Similar Threads
int can not be dereferenced error
Garbage Collection
Java Free Blocks
garbage collection question
// simple Question
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 20:21:45.