在Java中,GC日志能够帮助我们分析内存动态分配和垃圾回收,让我们有针对的对程序进行优化
先准备一个案例程序
public class GCTest {
public static void main(String[] args) {
int i = 0;
List userList = new ArrayList<>();
while (true) {
User user = new User("user" + i, i);
userList.add(user);
}
}
static class User {
private String userName;
private Integer age;
public User(String userName, Integer age) {
this.userName = userName;
this.age = age;
}
}
}
使用以下命令运行上面的程序
java -XX:+PrintGCDetails -XX:+PrintGCDateStamps -Xloggc:./gc-%t.log -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=10 -XX:GCLogFileSize=100M GCTest
参数介绍:
打印日志如下:
OpenJDK 64-Bit Server VM (25.312-b07) for linux-amd64 JRE (1.8.0_312-b07), built on Nov 13 2021 08:26:07 by "mockbuild" with gcc 8.5.0 20210514 (Red Hat 8.5.0-4)
Memory: 4k page, physical 12979592k(10600960k free), swap 4194304k(4194304k free)
CommandLine flags: -XX:GCLogFileSize=8192 -XX:InitialHeapSize=207673472 -XX:MaxHeapSize=3322775552 -XX:NumberOfGCLogFiles=5 -XX:+PrintGC -XX:+PrintGCDateStamps -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+UseCompressedClassPointers -XX:+UseCompressedOops -XX:+UseGCLogFileRotation -XX:+UseParallelGC
2022-04-14T07:52:06.521+0000: 0.073: [GC (Allocation Failure) [PSYoungGen: 51712K->8190K(59904K)] 51712K->34086K(196608K), 0.0534755 secs] [Times: user=0.46 sys=0.21, real=0.05 secs]
2022-04-14T07:52:06.855+0000: 0.406: [Full GC (Ergonomics) [PSYoungGen: 8176K->3053K(111616K)] [ParOldGen: 164547K->168844K(363008K)] 172723K->171898K(474624K), [Metaspace: 2946K->2946K(1056768K)], 1.3264231 secs] [Times: user=14.87 sys=0.20, real=1.33 secs]
Heap
PSYoungGen total 721408K, used 7219K [0x000000077df80000, 0x00000007c0000000, 0x00000007c0000000)
eden space 360960K, 2% used [0x000000077df80000,0x000000077e68ce50,0x0000000794000000)
from space 360448K, 0% used [0x0000000794000000,0x0000000794000000,0x00000007aa000000)
to space 360448K, 0% used [0x00000007aa000000,0x00000007aa000000,0x00000007c0000000)
ParOldGen total 1561600K, used 765K [0x00000006f9e00000, 0x0000000759300000, 0x000000077df80000)
object space 1561600K, 0% used [0x00000006f9e00000,0x00000006f9ebf6d8,0x0000000759300000)
Metaspace used 2982K, capacity 4486K, committed 4864K, reserved 1056768K
class space used 281K, capacity 386K, committed 512K, reserved 1048576K
日志详解
前三行日志信息都是JVM运行所在的环境信息以及启动参数,后面的信息才是我们需要关注的
【2022-04-14T07:52:06.521+0000: 0.073】:表示GC发生的时间
【GC(Allocation Failure)】:表示这是一次YGC,括号里面表示GC的原因,否则就是FGC
【PSYoungGen: 51712K->8190K(59904K)】:此次回收使用的是PS垃圾收集器,回收前年轻代大小->回收后年轻代大小(年轻代总大小)
【51712K->34086K(196608K)】:GC之前堆内存大小->GC之后堆内存大小
【0.0534755】:表示此次GC时间
GC easy
GC easy是一款GC日志分析工具。将GC日志上传到这款工具中能直接生成相关报表。GC easy链接地址