一. 安裝Memory Analyzer Tool
打開eclipse >> Help >> Install New Software >> 點擊Work With右邊的Add,輸入
[Name] MAT [Location] http://archive.eclipse.org/mat/1.2/update-site/
點擊OK >> 點擊Install 窗口下的Select All(選擇全部), 然后一直點 下一步 直到結束即可。
二.使用Memory Analyzer
創建java項目(只需一個類),代碼(類名OOMObject)

1 import java.util.ArrayList; 2 import java.util.List; 3 4 /** 5 * Created by foreverenjoy on 16-7-9. 6 */ 7 public class HeapOOM { 8 static class OOMObject { 9 10 } 11 12 public static void main(String[] args) { 13 List<OOMObject> list = new ArrayList<>(); 14 15 while (true) { 16 list.add(new OOMObject()); 17 } 18 } 19 }
在Debug Cofigurations中設置VM參數:
-Xms20m -Xmx20m -XX:+HeapDumpOnOutOfMemoryError
通過參數-XX:+HeapDumpOnOutOfMemoryError可以讓虛擬機在出現內存溢出異常時Dump出當前的內存堆轉存快照以便事后分析。
點擊debug運行項目,會出現
java.lang.OutOfMemoryError: Java heap space
Dumping heap to java_pid17179.hprof ...
Heap dump file created [27535550 bytes in 0.099 secs]

java_pid17179.hprof(虛擬機Dump出的內存堆轉存快照)文件可以用Memory Analyzer Tool進行分析。
點擊File >> Open File >> 選中本Java項目下的java_pid17179.hprof(java_*.hprof) >> 選中Leak Suspecs Report >> Finish
以下就是Memory Analyzer的分析結果