Objects eligible for garbage collection

前端 未结 5 2080
我寻月下人不归
我寻月下人不归 2020-12-03 12:41

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.

5条回答
  •  -上瘾入骨i
    2020-12-03 13:16

    Let's break this down line by line:

    CardBoard c1 = new CardBoard();
    

    We now have two objects, the CardBoard c1 points at and the Short c1.story. Neither is available for GC as c1 points at the CardBoard and the story variable of the CardBoard points at the Short...

    CardBoard c2 = new CardBoard();
    

    Similar to above, we now have four objects, none of which are available for GC.

    CardBoard c3 = c1.go(c2);
    

    We invoke the method go on the CardBoard pointed at by c1, passing the value of c2 which is a reference to a CardBoard Object. We null the parameter, but Java is pass by value meaning that the c2 variable itself is unaffected. We then return the nulled parameter. c3 is null, c1 and c2 are unaffected. We still have 4 objects, none of which can be GC'd.

    c1 = null;
    

    We null c1. The CardBoard object which c1 previously pointed at now has nothing pointing to it, and it can be GC'd. Because the story variable inside that CardBoard object is the only thing pointing at the Short, and because that CardBoard object is eligible for GC, the Short also becomes eligible for GC. This gives us 4 objects, 2 of which can be GC'd. The objects eligible for GC are the ones formerly referenced by c1 and c1.story.

提交回复
热议问题