OutOfMemoryError
OutOfMemoryError is thrown when the JVM cannot allocate more memory of a requested kind. The heap is full of reachable objects, or Metaspace, or native memory, depending on the message.
Detailed Explanation
Error is not an Exception you recover from casually. After OutOfMemoryError: Java heap space, the heap is exhausted. Catching it and continuing often leaves caches half-cleared and threads in a bad state. Log, dump if configured, and restart.
Read the suffix.
- Java heap space: live objects fill
-Xmx. Leak or heap too small. - GC overhead limit exceeded: the collector is working too hard for too little reclaimed (HotSpot may disable this check). Still a heap/live-set problem.
- Metaspace: too many classes loaded (leaking classloaders, huge generated code). Raise
MaxMetaspaceSizeonly after you fix the leak. - Unable to create native thread: OS thread limit, not Java heap. Too many platform threads.
- Direct buffer memory:
ByteBuffer.allocateDirectoff-heap cap. - Requested array size exceeds VM limit: you asked for an array larger than the VM allows, even if the heap is free.
-XX:+HeapDumpOnOutOfMemoryError writes a dump at the failure. That dump is how you tell leak from undersize. Runtime.maxMemory() is the heap max, not RSS. Native and metaspace sit outside it.
You reach for this page when a process dies with java.lang.OutOfMemoryError in the log. You fix the live set or the size. You do not catch OOM in a tight loop and retry new byte[].
The cost of a huge -Xmx on a small machine is swapping or a cgroup kill that looks like a crash without a Java OOM. Set heap and container limits together. The cost of catching Throwable and swallowing OOM is a zombie JVM.
StackOverflowError is a different error: stack frames, not heap. Do not confuse them.
Code Examples
public class HeapInfo {
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
System.out.println(rt.maxMemory() > 0); // prints: true
System.out.println(rt.totalMemory() > 0); // prints: true
}
}public class ArrayLimit {
public static void main(String[] args) {
try {
int[] xs = new int[Integer.MAX_VALUE];
System.out.println(xs.length);
} catch (OutOfMemoryError e) {
System.out.println(e.getClass().getSimpleName());
// prints: OutOfMemoryError
}
}
}Common Gotchas
Catching OOM and continuing is usually unsafe
restart after a dump.
The message after the colon names the pool
heap vs Metaspace vs threads vs direct.
Container memory limits can kill the process without a Java OOM
check cgroup RSS.
`StackOverflowError` is not heap exhaustion
`StackOverflowError` is not heap exhaustion