Java Programming - Garbage Collections - Discussion

7. 

class X2 
{
    public X2 x;
    public static void main(String [] args) 
    {
        X2 x2 = new X2();  /* Line 6 */
        X2 x3 = new X2();  /* Line 7 */
        x2.x = x3;
        x3.x = x2;
        x2 = new X2();
        x3 = x2; /* Line 11 */
        doComplexStuff();
    }
}
after line 11 runs, how many objects are eligible for garbage collection?

[A]. 0
[B]. 1
[C]. 2
[D]. 3

Answer: Option C

Explanation:

This is an example of the islands of isolated objects. By the time line 11 has run, the objects instantiated in lines 6 and 7 are referring to each other, but no live thread can reach either of them.


Ramu said: (Dec 9, 2010)  
i cant understand

Vik said: (Sep 9, 2014)  
Every time, when we create new X() we make not 1, but 2 objects (because one more object create in line 3 ).

That's why after line 11, we are eligible for garbage collection 2 object.
P.S.

Sorry for my English :)

Gayachand said: (Sep 16, 2014)  
Ans: 2 Object are garbage collected. Because,

public X2 x;
public static void main(String [] args)
{
X2 x2 = new X2(); /* Line 6 */
X2 x3 = new X2(); /* Line 7 */
x2.x = x3;
x3.x = x2;
x2 = new X2();
x3 = x2; /* Line 11 */
doComplexStuff();
}

Here the statement (x2.x = x3;) will hold new X2() object. And when x variable of type X hold another object called x2 at that moment one object garbage collected. G: x3 because one variable will hold one address. Not more than one variable.

And another object got garbage collected at the moment when we call x2 = new X2() ;

So total 2 object got garbage collected.

Bilal said: (Jul 9, 2018)  
The correct answer is C.

after main()
We assign the class X2's reference-id to x2(X2 x2=new X2()).
After it, we again assigning the reference-id of 2 to x3(X2 x3=new X2()).
So,x2 become eligible for GC.
Just before line 11 again reference-id of class X2 is going to x2 (x2=new X2).
therefor now x3 become eligible for GC.
That's why the answer is C.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.