namratanaik
namratanaik

Reputation: 25

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

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?

Upvotes: 1

Views: 1046

Answers (3)

matt freake
matt freake

Reputation: 5090

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

Upvotes: 3

user586399
user586399

Reputation:

Based on your code snippet, when the control reaches your "line 11", no objects can be GCed.

Reason:

  • Trees t; is a field, and thus cannot be GCed now.
  • after calling go, t2 will equal null. However, in method go, each t1 and t2 point to the other, plus that the field t is pointing to one of them. So that no object can be GCed, because of reference chain:

t -> t2

t2 -> t1

Upvotes: 1

Pablo
Pablo

Reputation: 3673

You create three objects:

Object "a": Trees t = new Trees();
Object "b": Trees t1 = new Trees();
Object "c": Trees t2 = new Trees();

At line 11, none of them are eligible for garbage collection, because the variable t (declared in main) still has a reference to object "a", and both "b" and "c" can be reached from "a".

Upvotes: 2

Related Questions