Java Programming - Garbage Collections - Discussion

Discussion Forum : Garbage Collections - General Questions (Q.No. 7)
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?
0
1
2
3
Answer: Option
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.

Discussion:
4 comments Page 1 of 1.

Gayachand said:   1 decade ago
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:   7 years ago
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.

Vik said:   1 decade ago
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 :)

Ramu said:   1 decade ago
i cant understand

Post your comments here:

Your comments will be displayed after verification.