一次OOM测试并分析
堆dump文件分析
Java代码:
public class HeapTest2 { static class OOMObject { private byte[] arrs = new byte[64 * 1024]; // 会占用64k的堆内存 } public static void fillHeap(int num) throws InterruptedException { List<OOMObject> oomObjects = new ArrayList<>(); for (int i = 0; i < num; i++) { Thread.sleep(50); oomObjects.add(new OOMObject()); // 不断创建OOMObject对象并将其添加到oomObjects中,使GCRoots可达 } } public static void main(String[] args) throws InterruptedException { fillHeap(1000); System.gc(); } }
JVM参数配置:
设置堆内存为20M,并在发生OOM自动生成堆dump文件
-Xms20m -Xmx20m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=C:\Users\17090889\Desktop\
运行后控制台输出:
java.lang.OutOfMemoryError: Java heap space Dumping heap to C:\Users\17090889\Desktop\java_pid5220.hprof ... Heap dump file created [20723289 bytes in 0.069 secs] Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at jvm.HeapTest2$OOMObject.<init>(HeapTest2.java:16) at jvm.HeapTest2.fillHeap(HeapTest2.java:23) at jvm.HeapTest2.main(HeapTest2.java:29) Process finished with exit code 1
通过使用 IBM HeapAnalyzer分析结果如下:
下载地址:(https://www.ibm.com/support/pages/ibm-heapanalyzer)
注意:IBM HeapAnalyzer工具启动命令为:java -Xmx2048m -jar ha.jar -Xmx参数为jvm最大内存,可依实际情况调整,尽量依本机内存情况调大,否则在找开较大的heapDump文件时易出现OOM
可以看到
19,148,784 bytes (96.54 %) of Java heap is used by 292 instances of jvm/HeapTest2$OOMObject |
OOMObject对象在堆内存中有292个,占据了19M,96%的堆内存空间导致内存溢出。
在之前的JVM参数中再加上 打印GC日志信息
-Xms20m -Xmx20m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=C:\Users\17090889\Desktop\ -XX:+PrintGCDetails -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintHeapAtGC -XX:+PrintGCDateStamps -Xloggc:C:\Users\17090889\Desktop\verbose.gc
待续...
线程core文件分析:
线程core中线程的几种状态:
NEW:未启动的,不会出现在Dump中
RUNNABLE:就绪的,在虚拟机内执行的
BLOCKED:受阻塞并等待监视器锁
WATING:无限期等待另一个线程执行特定操作
TIMED_WATING:有时限的等待另一个线程的特定操作
TERMINATED:已退出的
END.