背景
jvm发生gc之前,先检查老年代最大可用的连续空间是否大于新生代所有对象总空间。
如果条件成立,那这一次gc可以确保是安全的。
如果条件不成立,那先检查XX:HandlePromotionFailure参数的设置值是否允许担保失败,如果允许会继续检查老年代最大可用的连续空间是否大于历次晋升到老年代对象的平均大小:
如果大于,将尝试进行一次Minor GC,尽管这次Minor GC是有风险的;
如果小于,或者-XX:HandlePromotionFailure设置不允许冒险,那这时就要改为进行一次Full GC。
风险:如果发起Full GC会停顿时间较长。
注意:-XX:HandlePromotionFailure jdk 1.6以后就废弃了!
1.6后只要老年代的连续空间大于新生代对象总大小或者历次晋升的平均大小,就会进行Minor GC,否则将进行Full GC。
实现代码
代码语言:javascript复制package com.jvm.gc;
/**
* @author: csh
* @Date: 2020/12/9 17:41
* @Description:
*/
public class HandlePromotionFailureGC {
private static final int _1MB = 1024 * 1024;
/**
* VM参数:-Xms20M -Xmx20M -Xmn10M -XX: PrintGCDetails -XX:SurvivorRatio=8 -XX:HandlePromotionFailure=false
*/
@SuppressWarnings("unused")
public static void testHandlePromotion() {
byte[] allocation1, allocation2, allocation3, allocation4, allocation5, allocation6, allocation7;
allocation1 = new byte[2 * _1MB];
allocation2 = new byte[2 * _1MB];
allocation3 = new byte[2 * _1MB];
allocation1 = null;
allocation4 = new byte[2 * _1MB];
allocation5 = new byte[2 * _1MB];
allocation6 = new byte[2 * _1MB];
allocation4 = null;
allocation5 = null;
allocation6 = null;
allocation7 = new byte[2 * _1MB];
}
public static void main(String[] args) {
testHandlePromotion();
}
}
结果
注意这个GC是 Full GC
代码语言:javascript复制[GC (Allocation Failure) [PSYoungGen: 6301K->816K(9216K)] 6301K->4920K(19456K), 0.0041118 secs] [Times: user=0.00 sys=0.00, real=0.01 secs]
[GC (Allocation Failure) --[PSYoungGen: 7199K->7199K(9216K)] 11303K->15407K(19456K), 0.0031417 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
[Full GC (Ergonomics) [PSYoungGen: 7199K->0K(9216K)] [ParOldGen: 8208K->8821K(10240K)] 15407K->8821K(19456K), [Metaspace: 3427K->3427K(1056768K)], 0.0099859 secs] [Times: user=0.05 sys=0.00, real=0.01 secs]
Heap
PSYoungGen total 9216K, used 4535K [0x00000000ff600000, 0x0000000100000000, 0x0000000100000000)
eden space 8192K, 55% used [0x00000000ff600000,0x00000000ffa6dff0,0x00000000ffe00000)
from space 1024K, 0% used [0x00000000ffe00000,0x00000000ffe00000,0x00000000fff00000)
to space 1024K, 0% used [0x00000000fff00000,0x00000000fff00000,0x0000000100000000)
ParOldGen total 10240K, used 8821K [0x00000000fec00000, 0x00000000ff600000, 0x00000000ff600000)
object space 10240K, 86% used [0x00000000fec00000,0x00000000ff49d5f0,0x00000000ff600000)
Metaspace used 3447K, capacity 4496K, committed 4864K, reserved 1056768K
class space used 376K, capacity 388K, committed 512K, reserved 1048576K