测试程序

public class HeapOOM {
private static int i = 0; static class OOMObject {
} public static void main(String[] args) {
List<OOMObject> list = new ArrayList<OOMObject>();
try {
while (true) {
list.add(new OOMObject());
i++; }
} finally {
//
System.out.println(i);
} }
}

输出:

[GC (Allocation Failure)  5142K->3031K(19968K), 0.0070246 secs]
[GC (Allocation Failure) 8663K->7062K(19968K), 0.0066110 secs]
[GC (Allocation Failure) 12694K->12708K(19968K), 0.0091115 secs]
[Full GC (Ergonomics) 12708K->10719K(19968K), 0.1400352 secs]
[Full GC (Ergonomics) 16351K->14231K(19968K), 0.1051886 secs]
[Full GC (Ergonomics) 16799K->16622K(19968K), 0.1139390 secs]
[Full GC (Allocation Failure) 16622K->16593K(19968K), 0.1047700 secs]
java.lang.OutOfMemoryError: Java heap space
Dumping heap to java_pid11700.hprof ...
Heap dump file created [28412377 bytes in 0.082 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 HeapOOM.main(HeapOOM.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

使用Java VisualVM查看堆转储文件java_pid11700.hprof

可以看到OOMObject这个类有810326个实例,导致内存溢出OOM。

05-11 16:16