一 点睛
-XX:+HeapDumpOnOutOfMemoryError内存出现 OOM 时生成 Heap 转储文件,与下面这个参数互斥
-XX:+HeapDumpBeforeFullGC 出现 FullGC 时生成 Heap 转储文件,与上面这个参数互斥
-XX:HeapDumpPath=<path> 指定 heap 转储文件的存储路径,默认当前目录
-XX:OnOutOfMemoryError=<path> 指定一个可行性程序或脚本的路径,当发生 OOM 时执行脚本
二 实战
1 代码
package chapter03;
import java.util.ArrayList;
import java.util.Random;
/**
* -Xms600m -Xmx600m -XX:SurvivorRatio=8
* -XX:+HeapDumpOnOutOfMemoryError
* -XX:+HeapDumpBeforeFullGC
* -XX:HeapDumpPath=d:\HeapInstanceTest.hprof
* 老年代:400m
* 伊甸园:160m
* s0:20m
* s1:20m
*/
public class HeapInstanceTest {
byte[] buffer = new byte[new Random().nextInt(1024 * 1024)];
public static void main(String[] args) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
ArrayList<HeapInstanceTest> list = new ArrayList<>();
while (true) {
list.add(new HeapInstanceTest());
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
2 当参数配置为 -Xms600m -Xmx600m -XX:HeapDumpPath=d:\HeapInstanceTest.hprof -XX:+HeapDumpBeforeFullGC
Dumping heap to d:\HeapInstanceTest.hprof ...
Heap dump file created [444024614 bytes in 0.277 secs]
Dumping heap to d:\HeapInstanceTest.hprof.1 ...
Heap dump file created [601407984 bytes in 0.381 secs]
Dumping heap to d:\HeapInstanceTest.hprof.2 ...
Heap dump file created [599020322 bytes in 0.429 secs]
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
Dumping heap to d:\HeapInstanceTest.hprof.3 ...
Heap dump file created [598984886 bytes in 0.361 secs]
at chapter03.HeapInstanceTest.<init>(HeapInstanceTest.java:17)
at chapter03.HeapInstanceTest.main(HeapInstanceTest.java:27)
Process finished with exit code 1
生成文件如下
前3次是因为 FullGC 造成的,最后一次是因为 OOM造成的。
3 当参数配置为 -Xms600m -Xmx600m -XX:HeapDumpPath=d:\HeapInstanceTest.hprof -XX:+HeapDumpOnOutOfMemoryError
java.lang.OutOfMemoryError: Java heap space
Dumping heap to d:\HeapInstanceTest.hprof ...
Heap dump file created [577100327 bytes in 0.335 secs]
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at chapter03.HeapInstanceTest.<init>(HeapInstanceTest.java:17)
at chapter03.HeapInstanceTest.main(HeapInstanceTest.java:27)
生成文件如下
因为 OOM 生成 dump 文件。