MachineLove MachineLove - 1 month ago 17
Java Question

Eligibility of garbage collection

This code is a part of my class test -

class Bar { }
class Test
{
Bar doBar()
{
Bar b = new Bar(); /* Line 6 */
return b; /* Line 7 */
}
public static void main (String args[])
{
Test t = new Test(); /* Line 11 */
Bar newBar = t.doBar(); /* Line 12 */
System.out.println("newBar");
newBar = new Bar(); /* Line 14 */
System.out.println("finishing"); /* Line 15 */
}
}


At what point is the
Bar
object, created on
line 6
, eligible for garbage collection? Is it when
doBar()
completes?

Answer

All references to the Bar object created on line 6 are destroyed when a new reference to a new Bar object is assigned to the variable newBar on line 14. Therefore the Bar object, created on line 6, is eligible for garbage collection after line 14.

It isn't when doBar() completes because the reference in the doBar() method is returned on line 7 and is stored in newBar on line 12. This preserver the object created on line 6.