【注意】最后更新于 June 8, 2018,文中内容可能已过时,请谨慎使用。
OOM前排查
使用jmap导出当前堆dump进行离线分析
测试代码
1
2
3
4
5
6
7
8
9
10
11
12
|
public class MyTest {
private static List<String> list=new ArrayList<>();
public static void main(String[] args) throws InterruptedException {
for (int i=0;i<1000;i++){
list.add("111");
}
TimeUnit.SECONDS.sleep(60);
}
}
|
实时统计
导出dump
1
|
$ jmap -dump:live,format=b,file=dump.hprof <pid>
|
然后使用jhat或者MAT进行分析
OOM后排查
配置jvm参数-XX:+HeapDumpOnOutOfMemoryError -Xmx1m
测试代码
1
2
3
4
5
6
7
8
9
10
11
|
public class MyTest {
private static List<String> list=new ArrayList<>();
public static void main(String[] args) {
while (true){
list.add("111");
}
}
}
|
异常信息
1
2
3
4
5
6
7
8
9
10
11
|
java.lang.OutOfMemoryError: Java heap space
Dumping heap to java_pid4352.hprof ...
Heap dump file created [1933323 bytes in 0.053 secs]
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:3210)
at java.util.Arrays.copyOf(Arrays.java:3181)
at java.util.ArrayList.grow(ArrayList.java:261)
at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:235)
at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:227)
at java.util.ArrayList.add(ArrayList.java:458)
at com.catfish.MyTest.main(MyTest.java:15)
|
可以看到jvm自动导出了java_pid4352.hprof
使用jhat分析
1
2
3
4
5
6
|
$ jhat java_pid4352.hprof
Snapshot resolved.
Started HTTP server on port 7000
Server is ready.
|
可以通过访问 http://localhost:7000 来查看 dump 的数据
查看Show heap histogram

参考资料
JDK内建工具