JVM内存异常

1. Java堆内存溢出异常测试

JVM选项说明[^1]:

  • -Xms20m,设置堆的初始大小为20M
  • -Xmx20m,设置堆的最大大小为20M

代码[^2]:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.util.ArrayList;
import java.util.List;


* VM Args: -Xms20m -Xmx20m -XX:+HeapDumpOnOutOfMemoryError
*
* @author zzm
*
*/
public class {

static class OOMObject {
}

public static void main(String[] args) {
List<OOMObject> list = new ArrayList<>();
while (true) {
list.add(new OOMObject());
}

}

}

输出:当计算过程所需要的堆大小超出内存管理系统的能力时,JVM将抛出OutOfMemoryError[^3]。

1
2
3
4
5
6
7
8
9
10
11
java.lang.OutOfMemoryError: Java heap space
Dumping heap to java_pid10832.hprof ...
Heap dump file created [28036994 bytes in 0.089 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:265)
at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:239)
at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:231)
at java.util.ArrayList.add(ArrayList.java:462)
at ch02.HeapOOM.main(HeapOOM.java:18)

参考:
[^1]:Java8官方文档,https://docs.oracle.com/javase/8/docs/technotes/tools/windows/java.html
[^2]:《深入理解Java虚拟机》第2章
[^3]:jvm8规范,https://docs.oracle.com/javase/specs/jvms/se8/html/index.html