Search code examples
javascjp

Objects eligible for garbage collection


This question was taken from Kathy Sierra SCJP 1.6. How many objects are eligible for garbage collections?

According to Kathy Sierra's answer, it is C. That means two objects are eligible for garbage collection. I have given the explanation of the answer. But why is c3 not eligible for garbage collection (GC)?

class CardBoard {
    Short story = 200;
    CardBoard go(CardBoard cb) {
    cb = null;
    return cb;
}

public static void main(String[] args) {
    CardBoard c1 = new CardBoard();
    CardBoard c2 = new CardBoard();
    CardBoard c3 = c1.go(c2);
    c1 = null;
    // Do stuff
} }

When // Do stuff is reached, how many objects are eligible for GC?

  • A: 0
  • B: 1
  • C: 2
  • D: Compilation fails
  • E: It is not possible to know
  • F: An exception is thrown at runtime

Answer:

  • C is correct. Only one CardBoard object (c1) is eligible, but it has an associated Short wrapper object that is also eligible.
  • A, B, D, E, and F are incorrect based on the above. (Objective 7.4)

Solution

  • No object ever existed that c3 points to. The constructor was only called twice, two objects, one each pointed to by c1 and c2. c3 is just a reference, that has never been assigned anything but the null pointer.

    The reference c3, that currently points to null, won't go out of scope and be removed from the stack until the closing brace at the end of the main method is crossed.

    The object originally assigned to c1 is unreachable because the c1 reference was set to null, but the c2 reference has not been changed, so the object assigned to it is still reachable from this scope via the c2 reference.