Troubleshooting · Java & JVM
Java OutOfMemoryError? 7 causes, ranked
7 causes, most common first · last reviewed
TL;DR
Read the exact message first: 'Java heap space', 'Metaspace', 'unable to create native thread' and a container OOMKilled with no Java error are different problems. For heap errors, the question is whether heap used after full GC keeps climbing (a leak) or only spikes under load (too small, or one huge allocation). A heap dump answers it.
On this page
Quick triage: the first five minutes
Get the exact error and where the process died. A pod killed by the kernel shows exit code 137 and no Java stack trace.
Shellgrep -h 'OutOfMemoryError' app.log | sort | uniq -c kubectl get pod checkout-7d9f -o jsonpath='{.status.containerStatuses[0].lastState.terminated}' ; echoreason OOMKilled with exitCode 137 means the container limit was hit, which is outside the Java heap's control. Look at heap used after each garbage collection over time.
Shell# JDK 9+: unified GC logging java -Xlog:gc*:file=/var/log/app/gc.log:time,uptime -jar app.jar # live view of a running JVM jstat -gcutil <pid> 5sOld generation that stays full after each full GC and rises over hours is a leak. Make sure the next failure leaves evidence.
Shell-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dumps -XX:+ExitOnOutOfMemoryErrorWrite dumps to a volume that survives a restart and has room for one heap-sized file.
The causes, ranked
Most common first. The ranking is a judgement from how these failures usually turn out, not a measured statistic.
1. A memory leak: objects that are never released
What it looks like
- java.lang.OutOfMemoryError: Java heap space after hours or days of uptime, not at start.
- Heap used after full GC rises steadily; each GC frees less.
- GC runs more and more often and pause time climbs before the error.
How to confirm it
Take a heap dump or a class histogram from the running process and open the dump in a heap analyser such as Eclipse MAT. The dominator tree shows which objects keep the most memory alive, and the path to a GC root shows who holds them: often a static map, an unbounded cache, listeners never removed, or ThreadLocals in pooled threads.
jcmd <pid> GC.class_histogram | head -20
jcmd <pid> GC.heap_dump /dumps/app.hprofFix it now
Restart affected instances to buy time, staggered so capacity stays up, and keep one heap dump from before the restart. Then fix what holds the references: bound caches by size or time, remove listeners, clean up ThreadLocals. Compare two dumps taken hours apart if the leak is slow: the class whose instance count grows between them is the lead.
Prevent it
Use caches with explicit limits, track heap used after GC as a metric, and alert on a rising trend rather than on the error.
2. The heap is too small for the real workload
What it looks like
- Errors appear only under peak load, then stop when traffic falls.
- Heap after GC is high but flat over days; there is no upward trend.
- The heap was sized long ago, or left to a default chosen from container memory.
How to confirm it
Compare live data after full GC at peak with the maximum heap. If the working set at peak genuinely needs more, there is nothing to free. Check what the JVM actually chose for its maximum: without an explicit setting, recent JVMs size the heap as a share of the container's memory, which can be far smaller than people assume.
jcmd <pid> VM.flags | tr ' ' '\n' | grep -E 'MaxHeapSize|MaxRAMPercentage'Fix it now
Raise the heap, keeping room in the container for non-heap memory, or reduce work per instance and add instances.
# size the heap from the container limit instead of a fixed -Xmx
JAVA_TOOL_OPTIONS='-XX:MaxRAMPercentage=75.0'Prevent it
Load-test at peak with production heap settings, and record live data after GC in capacity planning.
3. One request loads far too much at once
What it looks like
- A sudden error on an instance that was healthy a moment ago.
- The stack trace points at reading a whole file, HTTP body or query result into memory, or building a large collection.
- Sometimes the message is 'Requested array size exceeds VM limit'.
How to confirm it
The stack trace in the error, and the largest objects in the heap dump, usually point straight at one request type: an export, a report, an unpaginated query. Correlate the time of the error with access logs to find the exact request and its parameters.
Fix it now
Limit the input (pagination, maximum page size, request size limits) and stream large results instead of buffering them.
Prevent it
Put explicit limits on every endpoint that returns or accepts collections, and test with the largest realistic customer.
4. Non-heap memory pushes the process past the container limit
What it looks like
- The container is OOMKilled (exit code 137) with no OutOfMemoryError in the logs.
- The heap looks healthy right up to the kill.
- The heap maximum is close to the container's memory limit.
How to confirm it
A JVM uses memory outside the heap: thread stacks, Metaspace, the code cache, direct buffers, GC structures. Native Memory Tracking breaks it down. If heap maximum plus these exceeds the limit, the kernel kills the process.
# start with tracking on (small overhead)
-XX:NativeMemoryTracking=summary
# then
jcmd <pid> VM.native_memory summaryFix it now
Lower the heap share of the container (for example 75% or less) or raise the container limit. Cap direct memory and thread counts if they are the large part.
Prevent it
Size containers as heap plus measured native memory plus headroom, not heap alone.
5. Metaspace fills with classes that are never unloaded
What it looks like
- java.lang.OutOfMemoryError: Metaspace.
- It happens after repeated redeploys in an application server, or in apps that generate classes at runtime: proxies, scripting, serialisation libraries.
- The number of loaded classes keeps rising.
How to confirm it
Watch loaded classes over time and check class loader statistics. A leaked class loader keeps every class it loaded.
jcmd <pid> VM.classloader_stats | head -20
jstat -class <pid> 10sFix it now
Restart to recover, then find what keeps old class loaders reachable, or stop generating new classes per request. Set -XX:MaxMetaspaceSize so a leak fails fast instead of consuming the container.
Prevent it
Cache generated classes and proxies instead of creating them repeatedly, and prefer restarting processes over hot redeploys.
6. Too many threads
What it looks like
- java.lang.OutOfMemoryError: unable to create native thread (older JDKs say 'unable to create new native thread').
- Thread count climbs steadily, often from executors created per request and never shut down.
- It can happen with plenty of heap free.
How to confirm it
Count threads and group them by name; a leak shows as hundreds of threads with the same name pattern. The operating system's process limit or the container's pids limit may also be the ceiling.
grep Threads /proc/<pid>/status
jcmd <pid> Thread.print | grep '^"' | sed 's/ #.*//; s/[0-9]\+"/N"/' | sort | uniq -c | sort -rn | headFix it now
Find the code that creates threads or executors and reuse a bounded pool instead. Restart to recover.
Prevent it
Create executors once, give pools explicit maximum sizes, and graph live thread count.
7. Direct buffer memory runs out
What it looks like
- java.lang.OutOfMemoryError: Direct buffer memory.
- Network-heavy code: Netty, NIO, HTTP clients and servers with large buffers.
- Process memory grows while heap stays flat.
How to confirm it
Direct buffers live outside the heap and are capped by -XX:MaxDirectMemorySize (by default about the maximum heap size). Native Memory Tracking and the BufferPool MBean show how much is used.
Fix it now
Find buffers that are allocated per request and not released (in Netty, reference-counted buffers that are never released) and fix the release path. Raise the cap only if usage is legitimate.
Prevent it
Turn on the framework's leak detection in test environments and graph direct memory in production.
Related concepts
FAQ
What does 'java.lang.OutOfMemoryError: Java heap space' mean?
The JVM could not allocate an object because the heap was full even after garbage collection. Either live data has outgrown the heap, something is leaking, or one operation tried to hold too much at once.
What is 'GC overhead limit exceeded'?
With the Parallel collector, the JVM throws it when it spends almost all its time in garbage collection while recovering very little memory. It is the same underlying problem as heap space, caught earlier.
Why was my Java container OOMKilled without an OutOfMemoryError?
The kernel killed the process for exceeding the container's memory limit. The heap may have been fine; thread stacks, Metaspace, direct buffers and other native memory count towards the limit too.
How do I take a heap dump from a running Java process?
Run jcmd <pid> GC.heap_dump with a file path. Add -XX:+HeapDumpOnOutOfMemoryError so the JVM writes one automatically when the error happens.
Related troubleshooting guides
- DatabasesDatabase connection pool exhausted? 7 causes, ranked
- KubernetesKubernetes HPA not scaling down? 6 causes, ranked
Reference documentation: Oracle Java troubleshooting guide: understand the OutOfMemoryError exception ↗ · Oracle documentation: the jcmd utility ↗ · Oracle documentation: Native Memory Tracking ↗ · Report a problem
Commands and settings are checked against the documentation linked above. Defaults change between versions; check the documentation for the version you run.