在阅读《深入理解Java虚拟机》中长期存活对象进入年老代这部分内容时,将书中代码运行了一遍,结果如下(运行环境:jdk1.8.0_172):
①当-XX:MaxTenuringThreshold=1时,运行结果与书中描述一致,allocation1对象在第二次GC发生时进入老年代。
[GC (Allocation Failure) [DefNew
Desired survivor size 524288 bytes, new threshold 1 (max 1)
- age 1: 790240 bytes, 790240 total
: 5335K->771K(9216K), 0.0031656 secs] 5335K->4867K(19456K), 0.0032127 secs] [Times: user=0.02 sys=0.00, real=0.00 secs]
[GC (Allocation Failure) [DefNew
Desired survivor size 524288 bytes, new threshold 1 (max 1)
: 4867K->0K(9216K), 0.0008847 secs] 8963K->4866K(19456K), 0.0009065 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
Heap
def new generation total 9216K, used 4178K [0x00000000fec00000, 0x00000000ff600000, 0x00000000ff600000)
eden space 8192K, 51% used [0x00000000fec00000, 0x00000000ff014930, 0x00000000ff400000)
from space 1024K, 0% used [0x00000000ff400000, 0x00000000ff400000, 0x00000000ff500000)
to space 1024K, 0% used [0x00000000ff500000, 0x00000000ff500000, 0x00000000ff600000)
tenured generation total 10240K, used 4866K [0x00000000ff600000, 0x0000000100000000, 0x0000000100000000)
the space 10240K, 47% used [0x00000000ff600000, 0x00000000ffac0b70, 0x00000000ffac0c00, 0x0000000100000000)
Metaspace used 2620K, capacity 4486K, committed 4864K, reserved 1056768K
class space used 280K, capacity 386K, committed 512K, reserved 1048576K
②当-XX:MaxTenuringThreshold=15时,运行结果与书中描述出现了偏差,allocation1对象在第二次GC发生时同样进入了老年代。
[GC (Allocation Failure) [DefNew
Desired survivor size 524288 bytes, new threshold 1 (max 15)
- age 1: 790240 bytes, 790240 total
: 5335K->771K(9216K), 0.0028299 secs] 5335K->4867K(19456K), 0.0028776 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
[GC (Allocation Failure) [DefNew
Desired survivor size 524288 bytes, new threshold 15 (max 15)
: 4867K->0K(9216K), 0.0008606 secs] 8963K->4866K(19456K), 0.0008757 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
Heap
def new generation total 9216K, used 4178K [0x00000000fec00000, 0x00000000ff600000, 0x00000000ff600000)
eden space 8192K, 51% used [0x00000000fec00000, 0x00000000ff014930, 0x00000000ff400000)
from space 1024K, 0% used [0x00000000ff400000, 0x00000000ff400000, 0x00000000ff500000)
to space 1024K, 0% used [0x00000000ff500000, 0x00000000ff500000, 0x00000000ff600000)
tenured generation total 10240K, used 4866K [0x00000000ff600000, 0x0000000100000000, 0x0000000100000000)
the space 10240K, 47% used [0x00000000ff600000, 0x00000000ffac0b70, 0x00000000ffac0c00, 0x0000000100000000)
Metaspace used 2620K, capacity 4486K, committed 4864K, reserved 1056768K
class space used 280K, capacity 386K, committed 512K, reserved 1048576K
上面运行结果中new threshold 1 (max 15)表示虚拟机自己计算的阈值为1 ,最大15。书中在-XX:MaxTenuringThreshold=15时,上面第一处标红的地方是new threshold 15 (max 15)。当在jdk 1.6.0_37环境下运行时,会看到和书中一致的结果。所以猜测可能是最新版的虚拟机做了改动。