Understanding Java OutOfMemoryError (OOM) and Common Types with Sample Code
This article explains what Java OutOfMemoryError (OOM) is, outlines the most common OOM types such as Java heap space, GC overhead limit, Metaspace, and native thread exhaustion, provides sample code for each, and suggests basic mitigation strategies like adjusting JVM options or optimizing code.
Welcome to follow the WeChat public account: Internet Full Stack Architecture.
Many Java programmers frequently encounter OutOfMemoryError (OOM), which can be difficult to resolve. This article introduces what OOM is, lists common OOM types, and presents basic solutions.
OOM stands for Out Of Memory, meaning a memory overflow that triggers an OutOfMemoryError exception during program execution. In the JVM runtime data area, only the program counter cannot cause an OOM.
Common OOM types include:
1. Java heap space
This is the most frequent OOM, indicating that the Java heap memory is exhausted. Example:
package com.sample.core.oom;
// heap memory overflow
public class HeapOOM {
public static void main(String[] args) {
String[] str = new String[10000 * 10000];
}
}Run the program with the VM option -Xmx10M to limit the maximum heap to 10 MB:
Executing the code produces an OOM exception:
Solution: increase the heap size or analyze the code to reduce excessive object allocation.
2. GC Overhead limit exceeded
This occurs when garbage collection consumes most of the CPU time (e.g., 89% of time) but recovers less than 2% of memory, causing the program to run very slowly.
package com.sample.core.oom;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
// Set VM parameter -Xmx10M to see the effect quickly
public class OverheadExceedOOM {
public static void main(String[] args) {
Map
map = new HashMap<>();
Random random = new Random();
while (true) {
map.put(random.nextInt(), "互联网全栈架构");
}
}
}Solution: increase heap memory or disable the check with -XX:-UseGCOverheadLimit , though the underlying issue should still be addressed.
3. Requested array size exceeds VM limit
This error indicates that an array size exceeds the VM's limit; it is relatively rare because most programs do not allocate arrays with billions of elements.
4. Metaspace
Metaspace stores class metadata outside the Java heap. When the metaspace runs out, an OOM is thrown. You can limit its size with -XX:MaxMetaspaceSize . Example:
package com.sample.core.oom;
public class MetaspaceOOM {
static javassist.ClassPool cp = javassist.ClassPool.getDefault();
public static void main(String[] args) throws Exception {
// Loop to load classes
for (int i = 0; i < 100000; i++) {
Class c = cp.makeClass("com.sample.core.oom.MetaspaceOOM" + i).toClass();
}
}
}Maven dependency for Javassist:
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.28.0-GA</version>
</dependency>Run with -XX:MaxMetaspaceSize=10M to reproduce the OOM:
5. unable to create new native thread
This occurs when the JVM requests a new thread but the operating system cannot allocate a native thread.
package com.sample.core.oom;
public class NewThreadOOM {
public static void main(String[] args) {
while (true) {
new Thread(() -> {
System.out.println(Math.random() + " ");
try {
Thread.sleep(10000000);
} catch (InterruptedException e) { }
}).start();
}
}
}On Linux, after running for a while, the following exception appears:
6. request size bytes for reason. Out of swap space
This exception is thrown when the local memory is insufficient, often related to OS configuration such as lacking swap space.
7. Compressed class space
On 64‑bit platforms, the JVM can use 32‑bit compressed class pointers. If the required space exceeds the value set by -XX:CompressedClassSpaceSize , a Compressed class space OOM occurs.
8. reason stack_trace_with_native_method
This occurs when native methods or JNI code fail to allocate required resources.
The article provides a basic introduction to OOM, demonstrates common types with sample code, and promises future posts on OOM troubleshooting techniques.
Thank you for reading! Please give a “like”, share, and follow to help the article reach more people.
References:
https://docs.oracle.com/javase/8/docs/technotes/guides/troubleshoot/memleaks002.html
https://www.geeksforgeeks.org/understanding-outofmemoryerror-exception-java/
Zhou Zhimin. Deep Understanding of the Java Virtual Machine . Mechanical Industry Press, 2011.
Recommended reading:
ZooKeeper Cluster Installation
Everywhere Java Annotations, Do You Really Get Them?
“Eight‑Sided” ZooKeeper Introduction
Responsibility Chain Pattern
Builder Pattern Discussion
Company Layoffs: Developers as “Accomplices” (Fiction)
Full-Stack Internet Architecture
Introducing full-stack Internet architecture technologies centered on Java
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.