本文内容如有错误、不足之处,欢迎技术爱好者们一同探讨,在本文下面讨论区留言,感谢。
简介
OutOfMemoryError 简称 OOM
OutOfMemoryError 异常是 JVM 所抛出的,当JVM没有足够的可用内存来分配时,就会抛出。OutOfMemoryError 在 Exception 类层次结构中属于 Error 类别。
继承关系
从继承关系中可以发现,OutOfMemoryError 继承 VirtualMachineError 虚拟机异常
分类
- Java heap space:Java 堆空间错误,应用程序尝试添加更多的数据放入堆空间区域,但没有足够的空间供它,可能会有大量的物理内存可用,但是 JVM 有堆大小限制。
- GC overhead limit exceeded:应用程序已经耗尽了几乎所有的可用内存并且GC一直未能回收它或只能回收2%的可用空间。
- Permgen space:表示永久代的内存区域被耗尽,永久生成主要由装入并存储到 PermGen 中的类声明组成,造成该错误的主要原因是永久区中装入了太多的类或太大的类。
- Metaspace:元空间中消息指示所述元空间区域在存储器中被耗尽。
- Unable to create new native thread:Java 应用程序已达到其可以启动线程数的限制。
- Out of swap space:交换空间也已用尽,并且由于缺少物理内存和交换空间,新的尝试分配失败。
- Requested array size exceeds VM limit:请求的数组大小超出VM限制时,这意味着因错误而崩溃的应用程序正试图分配一个大于 Java 虚拟机可以支持的数组。
例子
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是什么,以及它有哪些情况会产生和分类。
参考资料
介绍JVM中OOM的8种类型
What is an OutOfMemoryError and steps to find the root cause of OOM in Java?(什么是OutOfMemoryError以及查找Java中OOM根本原因的步骤?)