Garbage collection - why is c3 not eligible for collection in this example (SCJP 6) [duplicate]

旧时模样 提交于 2019-12-06 06:37:01

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/18875398/garbage-collection-why-is-c3-not-eligible-for-collection-in-this-example-scjp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!