Garbage collection - why is c3 not eligible for co

2019-04-11 08:45发布

This question already has an answer here:

Taken from SCJP 6 prep book -

Given:

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 // doStuff 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

The correct answer is C - " Only one CardBoard object (c1) is eligible, but it has an associated Short wrapper object that is also eligible."

My question is why is c3 not eligible for collection?

My thoughts are -

c1.go(c2) sets the local reference variable, cb (which is a copy of c2), to null and then returns cb which is assigned to c3. I know that the reference variable for c2 itself cannot be modified in the method, only the object behind it. However it would appear to me that the copy of the reference variable, cb, is set to null and assigned to c3. Why is c3 not set to the returned null in this instance?

2条回答
Explosion°爆炸
2楼-- · 2019-04-11 09:15

There is no object related to c3. Its value is null, so there's nothing to collect.

查看更多
Luminary・发光体
3楼-- · 2019-04-11 09:18

That SCJP "correct" answer is bogus. The right answer is either 4 or "It is not possible to know".

If the code is read literally ("// do Stuff" is just a comment), then the object previously reachable from c2 is just as dead and GC eligible as the one previously referred to from c1, and since both of those now-unreachable objects have a c1.story and c2.story objects that will also die with them, a total of 4 objects are eligible for collection.

However, if the "// do Stuff" thing is a placeholder for some unknown code, then that code may or may not use c2, which means that the object referred to by c2 may or may not be dead and eligible for collection when that code is reached. So if we don't know what "// do Stuff" actually is, it's either 2 or 4 that are eligible, and there is no way to tell which.

查看更多
登录 后发表回答