tags:

views:

159

answers:

1

Hi!

Question from SCJP test:

 class A{
      A aob;
      public static void main(String args[]){
           A a=new A();
           A b=new A();
           A c=new A();
           a.aob=b;
           b.aob=a;
           c.aob=a.aob;
           A d=new A().aob=new A();
           c=b;
           c.aob=null;
           System.gc();
      } 
  }

Question: after c.aob=null is executed, how many objects are eligible for garbage collection.

I think that 1, but correct answer 2. What's wrong?

+4  A: 

From Googling I found this thread.

The first object is the one referenced originally by c.

A a= new A();
A b= new A();
A c= new A();
a.aob=b;
b.aob=a;
c.aob=a.aob;
A d= new A().aob=new A();
c=b; //(1)

It becomes eligible at (1).

The other object eligible for GC is at statement

A d=new A().aob=new A();

Here the object created in the text in bold will be eligible for GC. The object in italicized text will be assigned to d.

Mark Byers
I agree! In general, the objects that are eligible for GC are the ones that cannot be reached by any reference. In more complicated scenarios, they are "isles" if inter-referenced objects that are not referenced by other objects outside that "isle".
Markos Fragkakis