MKod MKod - 6 months ago 13
Java Question

Garbage collection example in java?

class Beta { }

class Alpha {
static Beta b1 ;
Beta b2;
}

public class Tester {

public static void main(String[] args) {

Beta b1 = new Beta();
Beta b2 = new Beta();
Alpha a1 = new Alpha();
Alpha a2 = new Alpha();

a1.b1 = b1 ;
a1.b2 = b1 ;
a2.b2 = b2 ;

a1 = null ;
b1 = null;
b2 = null;

System.out.println(" Line 1 " + " a1 " + a1.b1);
System.out.println(" Line 2 " + " a1 " + a1.b2);
System.out.println(" Line 3 " + " a2 " + a2.b2);
System.out.println(" Line 4 " + " a1 " + a2.b1);
System.out.println(" Line 5 " + " b1 " + b1);
System.out.println(" Line 6 " + " b1 " + b2);

}

}


I am not sure why only a1 object is available for garbage collection in the above program. I am expecting a1 , b1 and b2 to be collected by garbage collector.

As you can see a1 , b1 and b2 were made NULL hence this is making objects to be available for garbage collection. If object is NULL or unreachable by any thread or reference variable it should be collected by garbage collector.

Can someone help me understand the subtleness of the above program with good example and in more precise way ? Your help is appreciated.

Answer

Because there is still reference exists to objects pointed by b1 & b2 refrences due to below lines.

a1.b1 = b1 ;
a1.b2 = b1 ;
a2.b2 = b2 ;

Assume like this:

  b1--->BetaObj1
    b2---BetaObj2
    a1---> AlphaObj1
    a2---> AlphaObj2

a1.b1 points to b1 that means, there is reference to BetaObj1 a1.b2 points to b1 that means, there is another reference to BetaObj1

(At this point there are 3 references to BetaObj1)

a2.b2 points to b2 that means, there is reference to BetaOBj2

(At this point there are 2 references to BetaObj2)

a1=null; makes AlphaObj1 eligible for GC

b1=null; makes BetaObj1 reference count to 2, so this object is not eligible for GC

b2=null; makes BetaObj2 reference count to 1, so this object is not eligible for GC.

Comments