當出現HeapDumpOnOutOfMemoryError錯誤時,我們需要分析原因,下面的程序就是模擬這個錯誤並導出dump文件,好讓你分析
GcTest.java
package gc; public class GcTest { private static final int _1MB= 1024 * 1024; //約1m public static void main(String[] args) { //總共約8m多,堆大小設置不超過8388608B即8.388608m就會內存溢出,但是需要整數,小於8M就會重現這個錯誤 byte[] a1, a2, a3, a4; a1 = new byte[2 * _1MB]; a2 = new byte[2 * _1MB]; a3 = new byte[2 * _1MB]; a4 = new byte[2 * _1MB]; } }
這個文件在桌面上,所以執行編譯:
執行 GcTest.bat:
set CLASSPATH=C:\Users\andy\Desktop\gc; java -Xms10M -Xmx10M -Xmn2M -XX:SurvivorRatio=8 -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=D:\study\log_hprof\gc.hprof -XX:+PrintGCDetails -Xloggc:D:\study\log_gc\gc.log gc.GcTest pause
結果如下:
gc.hprof文件用內存分析工具分析如mat打開 分析
User.java

package gc; import java.util.ArrayList; import java.util.List; /** * @Package gc * @ClassName: User * @Description: TODO(這里用一句話描述這個類的作用) * @author andy * @date 2013-6-9 下午4:46:13 */ public class User { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public User(String id, String name) { super(); this.id = id; this.name = name; } public static void main(String[] args) { List<User> list = new ArrayList<User>(); for (int i = 1; i < 10000; i++) { User o = new User(i + "", System.currentTimeMillis() + ""); list.add(o); o = null; } System.out.println("end"); try { Thread.sleep(100000000l); } catch (InterruptedException e) { e.printStackTrace(); } } }
運行user任務管理器查看到的pid號:
基於jmap導出的堆信息:
用裝了mat插件的eclipse打開firstHeap.bin文件
選擇Leak Suspects Reports模式,finish
點擊details