安装
在eclipse中点击 help
–>markerplace
,搜索memory
即可
测试代码
运行HeadOOm
需要设置jvm参数:-Xms20m -Xmx20m -XX:+HeapDumpOnOutOfMemoryError
public class HeadOOm {
public static void main(String[] args) {
TestList2 testList = new TestList2();
testList.test();
}
}
public class TestList2 {
List<TestClass> list = new ArrayList<>();
public void test() {
while (true) {
list.add(new TestClass());
}
}
}
eclipse可在这里设置
运行结果,在工程目录生成文件java_pid4888.hprof
java.lang.OutOfMemoryError: Java heap space
Dumping heap to java_pid4888.hprof ...
Heap dump file created [27989084 bytes in 0.096 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 priv.dengjili.memory.error.TestList2.test(TestList2.java:16)
at priv.dengjili.memory.error.HeadOOm.main(HeadOOm.java:20)
分析文件
双击文件java_pid4888.hprof
,打开文件主界面如图,这里我主要是讲解以下两种功能
Leak Suspects
这是最主要的功能,可以直接分析内存溢出情况,下面是打开主界面
点击See stacktrace.
,查看堆栈异常,基本上可以定位是哪一行代码出现oom
点击Details
查看一些对象的调用关系
点击list objects
,会出现
- with outgoing references
(调用了哪些对象)
- with incomming references
(被哪些对象调用了)
这里点击with incomming references
Histogram
双击Histogram
,可以看出各对象大概占用内存情况
也可以按照package分类,一目了然
讲到这里吧,后续有实用技能在更新