在idea中设置vm option为:
-Xms20m -Xmx20m -XX:+HeapDumpOnOutOfMemoryError
当出现oom时生成堆dump文件。
使用jvisualvm运行如下程序:
public class OOMTest {
static class OOMObject {
// int size_1M = 1024 * 1024;
// Byte[] bytes = new Byte[size_1M];
}
public static void main(String[] args) throws InterruptedException {
Thread.sleep(1000 * 10);
List<OOMObject> list = new ArrayList<>();
while (true) {
// Thread.sleep(100);
list.add(new OOMObject());
System.out.println(list.size());
}
}
}
程序运行后,idea控制台打印出:
540209
540210
540211
540212
540213
540214
540215
540216
540217
java.lang.OutOfMemoryError: Java heap space
Dumping heap to java_pid41805.hprof ...
Heap dump file created [21011140 bytes in 0.195 secs]
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:2245)
at java.util.Arrays.copyOf(Arrays.java:2219)
at java.util.ArrayList.grow(ArrayList.java:242)
at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:216)
at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:208)
at java.util.ArrayList.add(ArrayList.java:440)
at com.hao.laker.study.gc.OOMTest.main(OOMTest.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Process finished with exit code 1
将dump文件使用jvisualvm打开,分析如下:
Paste_Image.png
网友评论