Objects eligible for garbage collection

前端 未结 5 2094
我寻月下人不归
我寻月下人不归 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条回答
  •  隐瞒了意图╮
    2020-12-03 13:15

    The formally correct answer is that we don't know. And the reason we don't know is this line:

    Short story = 200;
    

    This compiles to the following byte code:

    CardBoard();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."":()V
       4: aload_0
       5: sipush        200
       8: invokestatic  #2                  // Method java/lang/Short.valueOf:(S)Ljava/lang/Short;
      11: putfield      #3                  // Field story:Ljava/lang/Short;
      14: return
    

    Line 8 is the key here, Short.valueOf(), which returns a boxed equivalent of the primitive 200. Let's look at the Javadoc of Short.valueOf():

    This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

    200 is out of the "must cache" range, and thus it falls under "may cache". If it is cached, the value of story won't be eligible for GC when its containing CardBoard instance is. If it isn't cached, story will be unreachable and thus GCed.

    To make the question unambiguous (and the proposed answer correct), the code should be amended like this:

    Short story = new Short(200);
    

    Update: The 1.6 Javadoc for Short.valueOf() is rather more cryptic than the 1.8 version I quoted, but the same logic applies: there is no way to tell just by looking at the code whether a new or a cached instance of Short will be returned.

提交回复
热议问题