什么是OutOfMemoryError以及查找Java中OOM根本原因的步骤?
该OutOfMemoryError异常 被抛出JVM,当JVM没有足够的可用内存,来分配。OutOfMemoryError 在Exception 类层次结构中属于Error类别。
产生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"); //记录信息,以便我们可以生成统计信息 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中的程序。该堆转储文件具有有关应用程序的内存使用情况的所有信息。