虚拟机提供了 -XX: +PrintGCDetails这个收集器日志参数,告诉虚拟机在发生垃圾收集行为时打印内存回收日志,并在进程退出的时候输出当前的内存各区域分配情况。
故根据这个情况,在IDEA中查看GC日志的步骤:
1.打开idea中的run选项卡中的Edit Configurations。之后,便是在刚刚打开的Run/Debug Configurations中点击左上角的加号,然后选"Application"
2.在左边详细信息中,将Main class设置为想要查看GC日志的类
3.在下面的VM options中输入-XX:+PrintGCDetails
,最后点击OK保存设置即可。
例子:
public class ReferenceCountingGC { public Object instance = null; private static final int _1MB = 1024 * 1024; private byte[] bigSize = new byte[2 * _1MB]; public static void main(String[] args) { ReferenceCountingGC objA = new ReferenceCountingGC(); ReferenceCountingGC objB = new ReferenceCountingGC(); objA.instance = objB; objB.instance = objA; System.gc(); } }
输出:
[GC (System.gc()) [PSYoungGen: 6763K->4872K(38400K)] 6763K->4880K(125952K), 0.0293377 secs] [Times: user=0.00 sys=0.00, real=0.03 secs] [Full GC (System.gc()) [PSYoungGen: 4872K->0K(38400K)] [ParOldGen: 8K->4721K(87552K)] 4880K->4721K(125952K), [Metaspace: 3435K->3435K(1056768K)], 0.0040781 secs] [Times: user=0.00 sys=0.01, real=0.00 secs] Heap PSYoungGen total 38400K, used 998K [0x00000000d5b00000, 0x00000000d8580000, 0x0000000100000000) eden space 33280K, 3% used [0x00000000d5b00000,0x00000000d5bf9b38,0x00000000d7b80000) from space 5120K, 0% used [0x00000000d7b80000,0x00000000d7b80000,0x00000000d8080000) to space 5120K, 0% used [0x00000000d8080000,0x00000000d8080000,0x00000000d8580000) ParOldGen total 87552K, used 4721K [0x0000000081000000, 0x0000000086580000, 0x00000000d5b00000) object space 87552K, 5% used [0x0000000081000000,0x000000008149c710,0x0000000086580000) Metaspace used 3447K, capacity 4496K, committed 4864K, reserved 1056768K class space used 376K, capacity 388K, committed 512K, reserved 1048576K