/**
* VM参数 :
* -verbose:gc
* -Xms20M
* -Xmx20M
* -Xmn10M
* -XX:+PrintGCDetails
* -XX:SurvivorRatio=8
* -XX:MaxTenuringThreshold=1 //年龄阈值,对象每熬过一次Minor GC,它的age会加1,age达到此值对象就会晋升老年代
* -XX:+PrintTenuringDistribution //输出对象年龄
* -XX:+UseSerialGC
*/
public class Main {
private static final int _1MB = 1024 * 1024;
public static void main(String[] args) {
byte[] b1, b2, b3;
b1 = new byte[_1MB / 4];
b2 = new byte[_1MB * 4];
b3 = new byte[_1MB * 4];
b3 = null;
b3 = new byte[_1MB * 4];
}
}
运行结果:
[GC (Allocation Failure) [DefNew
Desired survivor size 524288 bytes, new threshold 1 (max 1)
- age 1: 913424 bytes, 913424 total
: 6507K->892K(9216K), 0.0044971 secs] 6507K->4988K(19456K), 0.0045613 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
[GC (Allocation Failure) [DefNew
Desired survivor size 524288 bytes, new threshold 1 (max 1)
: 4988K->0K(9216K), 0.0016454 secs] 9084K->4984K(19456K), 0.0016760 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
Heap
def new generation total 9216K, used 4150K [0x00000000fec00000, 0x00000000ff600000, 0x00000000ff600000)
eden space 8192K, 50% used [0x00000000fec00000, 0x00000000ff00dbf8, 0x00000000ff400000)
from space 1024K, 0% used [0x00000000ff400000, 0x00000000ff400000, 0x00000000ff500000)
to space 1024K, 0% used [0x00000000ff500000, 0x00000000ff500000, 0x00000000ff600000)
tenured generation total 10240K, used 4984K [0x00000000ff600000, 0x0000000100000000, 0x0000000100000000)
the space 10240K, 48% used [0x00000000ff600000, 0x00000000ffade138, 0x00000000ffade200, 0x0000000100000000)
Metaspace used 3264K, capacity 4496K, committed 4864K, reserved 1056768K
class space used 357K, capacity 388K, committed 512K, reserved 1048576K
分析:
上面运行结果看出共发生了2次GC:
第一次GC是在第一次b3 = new byte[_1MB * 4];这行使得b1和b2引用的对象分配到老年代。
第二次GC是在第二次b3 = new byte[_1MB * 4];这行使得为b3第一次分配的对象GC掉了。