编写Java堆溢出代码
代码清单如下
import java.util.*;
/**
* Java堆内存溢出异常测试
* VM args: -Xms20m -Xmx20m -XX:+HeapDumpOnOutOfMemoryError
**/
public class OOME {
static class OOMObject{
}
public static void main(String [] args)
{
List<OOMObject> list = new ArrayList<OOMObject>();
while(true){
list.add(new OOMObject());
}
}
}
配置运行
Run -> Run Configuratinos配置如下:
在VM args处限制Java堆的大小为20MB,不可扩展(将堆的最小值-Xms参数与最大值参数-Xmx参数设置为一致即可避免堆的自动扩展),通过参数-XX:+HeapDumpOnOutOfMemoryError可以让虚拟机在出现内存溢出异常时Dump处当前的内存堆转储快照以便事后进行分析。
运行结果
java.lang.OutOfMemoryError: Java heap space
Dumping heap to java_pid14096.hprof …
Heap dump file created [27960943 bytes in 0.078 secs]
Exception in thread “main” java.lang.OutOfMemoryError: Java heap space
MAT打开堆转储快照文件
简单描述一下Eclipse中Memory Analysis tools插件的安装和使用,以下简称MAT。
- 安装
打开Eclipse-> Eclipse Marketplace下搜索Memory
然后直接安装Memory Analyzer - 打开
打开Windows->Perspective->Open Perspective->Other
得到下图的界面,点击Memory Analysis再点OK
- 打开快照文件
File->Open Heap Dump,然后到eclipse的workplace 打开产生的 java_pid14096.hprof 文件,得到如下图: