什麼是OutOfMemoryError以及查詢Java中OOM根本原因的步驟?
當JVM沒有足夠的可用記憶體進行分配時,JVM會丟擲OutOfMemoryError異常。OutOfMemoryError屬於Exception類層次結構中的錯誤類別。
生成OutOfMemoryError
- 我們將分配一大塊記憶體,這將耗盡堆記憶體儲存。
- 我們將不斷分配記憶體,直到達到JVM沒有足夠記憶體進行分配的點,這時將丟擲OutOfMemoryError異常。
- 一旦我們捕獲到OutOfMemory錯誤,就可以記錄該錯誤。
示例
public class OutOfMemoryErrorDemo {
public static void main(String[] args) throws Exception {
int dummyArraySize = 15;
System.out.println("Max JVM memory: " + Runtime.getRuntime().maxMemory());
long memoryConsumed = 0;
try {
long[] memoryAllocated = null;
for(int loop = 0; loop < Integer.MAX_VALUE; loop++) {
memoryAllocated = new long[dummyArraySize];
memoryAllocated[0] = 0;
memoryConsumed += dummyArraySize * Long.SIZE;
System.out.println("Memory Consumed till now: " + memoryConsumed);
dummyArraySize *= dummyArraySize * 2;
Thread.sleep(500);
}
} catch (OutOfMemoryError outofMemory) {
System.out.println("Catching out of memory error");
//Log the information, so that we can generate the statistics
throw outofMemory;
}
}
}輸出
Max JVM memory: 119537664 Memory Consumed till now: 960 Memory Consumed till now: 29760 Memory Consumed till now: 25949760 Catching out of memory error Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at OutOfMemoryErrorDemo.main(OutOfMemoryErrorDemo.java:9)
查詢OOM根本原因的步驟
步驟1:在OutOfMemoryError時生成堆轉儲
使用VM引數 -XX:+HeapDumpOnOutOfMemoryError啟動應用程式。這將告訴JVM在發生OOM時生成堆轉儲。
$ java -XX:+HeapDumpOnOutOfMemoryError ...
步驟2:重現問題
如果我們無法在開發環境中重現問題,我們可能需要使用生產環境。當我們重現問題並且應用程式丟擲OOM時,它將生成一個堆轉儲檔案。
步驟3:使用堆轉儲檔案調查問題
使用VisualVM讀取堆轉儲檔案並診斷問題。VisualVM是一個位於JDK_HOME/bin/jvisualvm中的程式。堆轉儲檔案包含有關應用程式記憶體使用情況的所有資訊。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP