什么是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