Sub topic 12
Understanding OutOfMemoryError
This chapter assumes you know the heap, Metaspace and the generational layout from earlier chapters, and that you can run java and jcmd from a terminal. You will learn to read the message after java.lang.OutOfMemoryError: and map it to the memory area that ran out. You will also learn to capture evidence at the moment of failure.
What the error means
OutOfMemoryError (OOME) is a subclass of VirtualMachineError, so it is an Error and not an Exception. The JVM throws it when it cannot satisfy a request for memory and the garbage collector cannot free enough. "Memory" here covers more than the heap. The text after the colon tells you which resource ran out, so always read it before changing any flags.
A common mistake is to raise -Xmx after every OOME. That helps only when the message is Java heap space and the application has a real working set larger than the heap. For a leak it delays the failure. For other messages it does nothing, because the exhausted resource is outside the heap.
The messages and their causes
| Message | Area exhausted | Typical cause | First check |
|---|---|---|---|
| `Java heap space` | Heap | Leak, or live data larger than `-Xmx` | Heap dump, dominator tree |
| `GC overhead limit exceeded` | Heap | Heap nearly full, GC thrashing | Same as above, plus GC log |
| `Requested array size exceeds VM limit` | Heap | Array length near `Integer.MAX_VALUE` | Code that computes sizes |
| `Metaspace` | Class metadata | Class loader leak, runaway class generation | `jcmd <pid> GC.class_histogram`, loaded class count |
| `Compressed class space` | Class metadata | Very many classes with compressed class pointers | `-XX:CompressedClassSpaceSize` |
| `unable to create native thread` | OS threads | Too many threads, OS or container limit | Thread count, `ulimit -u`, `-Xss` |
| `Direct buffer memory` | Off-heap buffers | Unreleased `ByteBuffer.allocateDirect` buffers | `-XX:MaxDirectMemorySize`, NIO usage |
Java heap space
This is the most common message. The allocator could not find room in the heap, even after a full collection. There are two root causes:
- A leak. Objects stay reachable from a GC root and the live set grows without bound. The static list in the
LeakDemoprogram below is the simplest case. - An undersized heap. The live set is legitimate but larger than
-Xmx, for example a service that loads a big dataset on startup.
A single huge allocation can also trigger it. Asking for a 600 MB array in a 512 MB heap fails immediately, whatever the rest of the heap holds.
import java.util.ArrayList;
import java.util.List;
public class LeakDemo {
private static final List<byte[]> CACHE = new ArrayList<>();
public static void main(String[] args) {
while (true) {
CACHE.add(new byte[1024 * 1024]); // 1 MB kept reachable from a static field
}
}
}Run it with a small heap so it fails quickly:
java -Xms512m -Xmx512m -XX:+UseG1GC -Xlog:gc*:file=gc.log LeakDemoIn gc.log you will see collections that free less and less each time, until a full collection recovers almost nothing. That pattern is the signature of a leak. A healthy application shows a sawtooth: heap usage after each collection returns to roughly the same floor.
GC overhead limit exceeded
The Parallel collector throws this when the JVM spends more than about 98% of its time in garbage collection and recovers less than about 2% of the heap, several times in a row. It is an early warning of the same problem as Java heap space: the heap is almost full of live data. The application is technically still running but makes almost no progress.
The check is a feature of the Parallel collector. G1 and ZGC do not use it, so on those collectors the same situation ends in Java heap space or in a very slow application. You can switch the check off with -XX:-UseGCOverheadLimit, but that only trades a fast failure for a slow one.
Requested array size exceeds VM limit
The program asked for an array whose length is close to Integer.MAX_VALUE, which the JVM cannot allocate regardless of heap size. Raising -Xmx will not fix it. Look for size calculations that overflow or that trust external input, such as a length read from a network message.
Metaspace and Compressed class space
Metaspace holds class metadata in native memory. By default it grows until the operating system refuses, so the error appears only when you set -XX:MaxMetaspaceSize or the machine itself runs out. A class can be unloaded only when its class loader becomes unreachable. The usual causes are:
- Redeploying a web application without the old class loader being released, because a thread, a
ThreadLocalor a driver registration still points at it. - Libraries that generate classes at run time (proxies, bytecode generators, scripting engines) without caching them.
Compressed class space is a separate fixed-size region, 1 GB by default, used when compressed class pointers are on. Its message appears when the count of classes exhausts that region even though general Metaspace has room.
unable to create native thread
Each Java thread needs a native thread and its own stack, allocated outside the heap. This error means the operating system refused to create one. Causes include:
- An unbounded pool, such as
Executors.newCachedThreadPool()fed faster than tasks finish. - A per-user process limit (
ulimit -u) or a container PID limit. - Too little free native memory, made worse by a large
-Xss.
Enlarging the heap makes this worse, because it takes memory away from the native side. Bound the thread pools, and reduce -Xss only if you know the stack depth your code needs.
Direct buffer memory
ByteBuffer.allocateDirect reserves memory outside the heap. The limit defaults to roughly the maximum heap size and can be set with -XX:MaxDirectMemorySize. The Java object for a direct buffer is tiny, so the heap may look healthy while native memory fills up. The native block is freed only after the buffer object is collected. This program shows the failure with a low limit:
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
public class DirectDemo {
public static void main(String[] args) {
List<ByteBuffer> buffers = new ArrayList<>();
try {
while (true) {
buffers.add(ByteBuffer.allocateDirect(1024 * 1024));
}
} catch (OutOfMemoryError e) {
System.out.println("Allocated " + buffers.size() + " MB, then: " + e);
}
}
}java -XX:MaxDirectMemorySize=64m DirectDemoThe exact message text differs between JDK versions, but it always mentions direct buffer memory.
When the JVM does not throw anything
Some out-of-memory failures never reach Java code. If the process exceeds its memory limit, the Linux OOM killer, or the container runtime, ends it with SIGKILL. You get no stack trace and no heap dump, and the exit status is usually 137. Check dmesg or the container's events for the kill record.
This happens when heap plus Metaspace, thread stacks, direct buffers and the JVM's own overhead exceed the limit, even though the heap alone is within bounds. In containers, size the heap as a fraction of the limit, for example -XX:MaxRAMPercentage=70, and leave headroom for everything else.
Handling and catching OOME
You can catch OutOfMemoryError, but be careful about what you do next. The failed allocation may have left the application in a half-updated state, and other threads may hit the same error at arbitrary points. Reasonable uses are:
- Failing one isolated, large operation, for example rejecting a huge upload, when you know that operation caused the shortage.
- Logging a final message and shutting down.
For services, it is usually safer to let the process die and restart cleanly. Two flags support this:
-XX:+ExitOnOutOfMemoryErrorends the JVM at the first OOME.-XX:+CrashOnOutOfMemoryErroraborts and produces a crash file, which is useful for native-level analysis.
Pair either flag with a supervisor (systemd, Kubernetes) that restarts the process.
Capturing evidence
An OOME is hard to reproduce, so configure capture before it happens:
java -Xmx256m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=./dumps LeakDemo
jcmd <pid> GC.heap_info
jcmd <pid> GC.class_histogramThe first command writes an .hprof file when the heap fills. Create the dumps directory first and make sure the disk has room, since a dump is about as large as the used heap. Open the file in a tool such as Eclipse MAT or VisualVM and look at the dominator tree: the objects that retain the most memory, and the reference path from a GC root to each one, usually point straight at the leak.
The jcmd commands work on a live process. GC.heap_info shows occupancy, and GC.class_histogram lists instance counts and bytes per class. Run the histogram twice a few minutes apart. The class whose count keeps climbing is your suspect.
A small program can show the numbers your flags produce:
public class MemoryInfo {
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
long mb = 1024 * 1024;
System.out.println("Max heap: " + rt.maxMemory() / mb + " MB");
System.out.println("Total heap: " + rt.totalMemory() / mb + " MB");
System.out.println("Free heap: " + rt.freeMemory() / mb + " MB");
}
}Triage workflow
Common mistakes
- Reading only the exception class and ignoring the message text.
- Setting
-Xmxequal to the container limit, which leaves no room for Metaspace, stacks and buffers. - Writing the heap dump to a small disk, so the dump fails or fills the volume.
- Catching
OutOfMemoryErrorin a loop and continuing as if nothing happened. - Assuming a
Metaspaceerror means the heap is too small.
Exercise
A service in a container with a 1 GB memory limit runs with -Xmx1g. It restarts every few hours with exit status 137, and no heap dump is ever written. Why does this happen, and what would you change?
Show answer
Exit status 137 means the process received SIGKILL, here from the container's OOM killer, so the JVM never had a chance to throw OutOfMemoryError or write a dump. The heap alone is allowed to use the whole 1 GB limit, and Metaspace, thread stacks, direct buffers and JVM overhead push total process memory past it. Reduce the heap to leave headroom, for example -XX:MaxRAMPercentage=70 or a smaller -Xmx, and check the container events or dmesg to confirm the kill.
Exercise
You see "java.lang.OutOfMemoryError: Metaspace" after several redeployments of a web application on a running server, while heap usage stays low. What is the likely cause, and which evidence would confirm it?
Show answer
The old class loaders from earlier deployments are probably still reachable, for example through a thread, a ThreadLocal or a registered driver, so their classes cannot be unloaded and Metaspace fills up. Confirm it by comparing the loaded class count over time, and by running jcmd <pid> GC.class_histogram or opening a heap dump to find multiple instances of the application's class loader. Raising -XX:MaxMetaspaceSize only delays the error.