how to determine which objects are eligible for garbage collection in the given program?

advertisements

Given:

 public class Trees {
    Trees t;

    public static void main(String[] args) {
        Trees t = new Trees();
        Trees t2 = t.go(t);
        t2 = null;
        // more code here : LINE 11
    }

    Trees go(Trees t) {
        Trees t1 = new Trees();
        Trees t2 = new Trees();
        t1.t = t2;
        t2.t = t1;
        t.t = t2;
        return t1;
    }
}

When line 11 is reached, how many objects are eligible for garbage collection?


You have asked how to determine the number of objects eligible for gc. The easiest way to work these questions out is to draw a diagram showing references (t, t1, t2, in your example) and the actual objects themselves. Once an object is not connected to any reference, there is no way for the Java code to access it, so it is then eligible for collection.

This link shows an example and how to draw a diagram

http://radio.javaranch.com/corey/2004/03/25/1080237422000.html