Heap memory cleanup

exercise No. 266

Q:

We consider:

class X2 
{
    public X2 x;
    public static void main(String [] args) 
    {
        X2 x2 = new X2();  
        X2 x3 = new X2(); 
        x2.x = x3;
        x3.x = x2;
        x2 = new X2();
        x3 = x2;
        {
          X2 x4 = new X2();
        }
    }
}

How many objects may be garbage collected when main(...) ends? Explain your result.

A:

We step through our code:

X2 x2 = new X2()

Instance 1 referenced by: x2

X2 x3 = new X2()

Instance 2 referenced by: x3

x2.x = x3

Instance 2 referenced by: x3, x2.x

x3.x = x2

Instance 1 referenced by: x2, x3.x

x2 = new X2()

Instance 1 referenced by: x3.x

Instance 2 referenced by: x3

Instance 3 referenced by: x2

x3 = x2

Instance 1 referenced by: -, gets garbage collected

Instance 2 Referenced by: -, gets garbage collected

Instance 3 referenced by: x2, x3

X2 x4 = new X2()

Instance 4 referenced by: x4

End of block:

Instance 4 referenced by: -, gets garbage collected

Thus three objects will be garbage collected.