记个笔记,手写一个测试类,模拟堆内存溢出。
/**
* 堆内存溢出测试类
* VM Agrs: -Xms10m -Xmx10m -XX:+HeapDumpOnOutOfMemoryError
* @author lixiang
* @date 2019年04月12日 - 14:44
* @history 2019年04月12日 - 14:44 lixiang create.
*/
public class HeapOOM {
static class TestObject {
}
public static void main(String[] args) {
Integer counter = 0;
List<TestObject> list = new ArrayList<>();
while (true) {
counter ++;
list.add(new TestObject());
System.out.println(counter);
}
}
}
注意配置虚拟机参数:将堆的最小值 -Xms 参数与最大值 -Xmx 参数设置成一样即可避免堆自动扩展,通过参数 -XX:+HeapDumpOnOutOfMemoryError 可以让虚拟机在出现内存溢出异常时Dump出当前的内存堆转储快照以便事后进行分析。
运行结果: