2016年7月7日星期四

Java_026:使用 MAT 分析 Heap Dump

环境:MAC OS X 10.11.5 + Oracle JDK 1.7.0_80 + MAT 1.6.0

MAT(Memory Analyzer Tool) 是一个 Java Heap 内存分析工具,是解决 OutOfMemoryError 的利器。
它可以快速的计算出内存中所有对象的数量以及占用空间,查找内存泄露,还可以看到是哪个对象阻止了垃圾收集器的回收工作。
下载地址:http://www.eclipse.org/mat/,安装很简单,解压即可。
MAT 可以离线分析 HPROF 格式的 heap dump 二进制文件。

MAT 有以下几种视图帮助我们分析:
(1)Biggest object by retained size:以饼状图列出系统中占用最大资源的对象。
(2)Histogram:以直方图的形式列出每个实例的详细信息。
(3)Dominator Tree:列出最大的对象和保持其存活的对象。
(4)Top Consumers:显示出最耗资源的对象信息。
(5)Duplicate Classes:显示重复类信息。
(6)Leak Suspects:内存泄露嫌疑对象。

1. 如何获得 heap dump 文件?
(1)jmap -dump:format=b,file=/tmp/heap.bin PID
(2)-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp
(3)-XX:+HeapDumpOnCtrlBreak -XX:HeapDumpPath=/tmp

2. shallow heap 和 retained heap
shallow heap 指的是对象本身占用内存的大小,不包含对其它对象的引用,也就是对象头加成员变量(不是成员变量的值)的总和。
retained heap 指的是对象本身的 shallow heap,加上从该对象能直接或间接访问到对象的 shallow heap 之和。
retained heap 是该对象被 GC 之后所能回收到内存的总和。

3. with incoming references 和 with outgoing references
List objects 有两个选项:with incoming references 和 with outgoing references。
with incoming references 表示的是当前查看的对象被外部引用的情况。
with outgoing references 表示的是当前查看的对象引用的外部对象。

4. 对比前后两次的 Heap Dump 

5. 通过 Merge Shortest Paths to GC Roots 找出某个实例没有被释放的原因

参考文献:
1. http://blog.csdn.net/rachel_luo/article/details/8990202
2. http://blog.csdn.net/rachel_luo/article/details/8992461
3. http://blog.csdn.net/rachel_luo/article/details/8992720
4. http://www.xuebuyuan.com/1656657.html
5. http://www.cnblogs.com/TestWorld/p/5681028.html
6. http://www.tuicool.com/articles/If2MVr