测试代码如下:
public class TestMinorGC {
private static final int _1M = 1024 * 1024;
public static void testAllocation(){
byte[] allocation1, allocation2, allocation3, allocation4;
allocation1 = new byte[2*_1M];
allocation2 = new byte[2*_1M];
allocation3 = new byte[2*_1M];
allocation4 = new byte[4*_1M];
}
public static void main(String[] args) {
testAllocation();
}
}
JDK新生代默认收集器是Parallel Scavenge。
JVM参数配置如下:
-Xms20M -Xmx20M -Xmn10M -XX:SurvivorRatio=8 -XX:+PrintGCDetails
运行结果如下:
Heap
PSYoungGen total 9216K, used 7292K [0x00000000ff600000, 0x0000000100000000, 0x0000000100000000)
eden space 8192K, 89% used [0x00000000ff600000,0x00000000ffd1f3d0,0x00000000ffe00000)
from space 1024K, 0% used [0x00000000fff00000,0x00000000fff00000,0x0000000100000000)
to space 1024K, 0% used [0x00000000ffe00000,0x00000000ffe00000,0x00000000fff00000)
ParOldGen total 10240K, used 4096K [0x00000000fec00000, 0x00000000ff600000, 0x00000000ff600000)
object space 10240K, 40% used [0x00000000fec00000,0x00000000ff000010,0x00000000ff600000)
Metaspace used 2660K, capacity 4486K, committed 4864K, reserved 1056768K
class space used 286K, capacity 386K, committed 512K, reserved 1048576K
使用Serial收集器,增加JVM参数 -XX:+UseSerialGC。
运行结果如下:
[GC (Allocation Failure) [DefNew: 7128K->550K(9216K), 0.0063592 secs] 7128K->6694K(19456K), 0.0064370 secs] [Times: user=0.02 sys=0.00, real=0.01 secs]
Heap
def new generation total 9216K, used 4728K [0x00000000fec00000, 0x00000000ff600000, 0x00000000ff600000)
eden space 8192K, 51% used [0x00000000fec00000, 0x00000000ff014930, 0x00000000ff400000)
from space 1024K, 53% used [0x00000000ff500000, 0x00000000ff589a78, 0x00000000ff600000)
to space 1024K, 0% used [0x00000000ff400000, 0x00000000ff400000, 0x00000000ff500000)
tenured generation total 10240K, used 6144K [0x00000000ff600000, 0x0000000100000000, 0x0000000100000000)
the space 10240K, 60% used [0x00000000ff600000, 0x00000000ffc00030, 0x00000000ffc00200, 0x0000000100000000)
Metaspace used 2660K, capacity 4486K, committed 4864K, reserved 1056768K
class space used 286K, capacity 386K, committed 512K, reserved 1048576K
结果对比可知:
PS收集器没有GC,4M的对象直接分配在了老年代。如果将对象大小改为3M或2M,将触发GC。
Serial收集器下,给4M的对象分配内存时触发了一次GC。GC产生的结果:6M的对象进入了老年代,4M的对象分配在了新生代。
Serial收集器下增加 -XX:PretenureSizeThreshold=3145728可产生PS收集器相同的结果。