很多时候我们在学习JVM时,往往需要查看JVM的回收日志,查看JVM的相关运行参数,这时候我们可以通过手动触发的形式获取JVM的运行回收情况。

加上参数

-Xms1024m -Xmx1024m -Xmn512m -XX:+PrintGCDetails。

手动触发gc

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class TestGCRoots01 {
private int _10MB = 10 * 1024 * 1024;
private byte[] memory = new byte[8 * _10MB];

public static void main(String[] args) {
method01();
System.out.println("返回main方法");
System.gc();
System.out.println("第二次GC完成");
}

public static void method01() {
TestGCRoots01 t = new TestGCRoots01();
System.gc();
System.out.println("第一次GC完成");
}
}

关键的一行在于 System.gc();

运行结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[GC (System.gc()) [PSYoungGen: 97648K->624K(458752K)] 97648K->82552K(983040K), 0.0805172 secs] [Times: user=0.06 sys=0.04, real=0.08 secs] 
[Full GC (System.gc()) [PSYoungGen: 624K->0K(458752K)] [ParOldGen: 81928K->82426K(524288K)] 82552K->82426K(983040K), [Metaspace: 3305K->3305K(1056768K)], 0.0252976 secs] [Times: user=0.02 sys=0.00, real=0.03 secs]
第一次GC完成
返回main方法
[GC (System.gc()) [PSYoungGen: 7864K->64K(458752K)] 90291K->82490K(983040K), 0.0017362 secs] [Times: user=0.01 sys=0.00, real=0.00 secs]
[Full GC (System.gc()) [PSYoungGen: 64K->0K(458752K)] [ParOldGen: 82426K->494K(524288K)] 82490K->494K(983040K), [Metaspace: 3306K->3306K(1056768K)], 0.0115159 secs] [Times: user=0.01 sys=0.00, real=0.01 secs]
第二次GC完成
Heap
PSYoungGen total 458752K, used 23593K [0x00000007a0000000, 0x00000007c0000000, 0x00000007c0000000)
eden space 393216K, 6% used [0x00000007a0000000,0x00000007a170a568,0x00000007b8000000)
from space 65536K, 0% used [0x00000007bc000000,0x00000007bc000000,0x00000007c0000000)
to space 65536K, 0% used [0x00000007b8000000,0x00000007b8000000,0x00000007bc000000)
ParOldGen total 524288K, used 494K [0x0000000780000000, 0x00000007a0000000, 0x00000007a0000000)
object space 524288K, 0% used [0x0000000780000000,0x000000078007bb70,0x00000007a0000000)
Metaspace used 3313K, capacity 4496K, committed 4864K, reserved 1056768K
class space used 365K, capacity 388K, committed 512K, reserved 1048576K