Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java: OutOfMemoryError Java heap space and how to size it

Heap exhaustion is a live-set problem, not only a small -Xmx. Read GC logs, capture a heap dump, find the retention path, and size the heap from evidence.

~5 min readJava
#java#jvm#outofmemoryerror#garbage-collection
Bold white headline reading HEAP EXHAUSTED with a JVM crate overflowing amber data blocks above a cyan meter.

Introduction & Quick Summary

The JVM stops with an error that names the heap, not a class:

code
Exception in thread "http-nio-8080-exec-7" java.lang.OutOfMemoryError: Java heap space at java.base/java.util.Arrays.copyOf(Arrays.java:3537) at java.base/java.lang.AbstractStringBuilder.<init>(AbstractStringBuilder.java:123) at java.base/java.lang.StringBuilder.<init>(StringBuilder.java:99) at com.acme.report.ReportBuilder.render(ReportBuilder.java:64)
code
Dumping heap to /tmp/java_pid1.hprof ... Heap dump file created [2147483648 bytes in 6.214 secs]

Java heap space means the JVM could not allocate an object because the heap was already full after a full garbage collection. The stack is where the allocation failed, which is almost never where the memory is retained. Fixing it means finding what is holding references, not adding memory blindly.

Where it appears:

  • A report or export job that materializes a full table into a List.
  • A cache with no eviction, keyed by request or user id.
  • A container whose heap limit was sized for a VM and not for the container limit.
  • A batch that grows a String in a loop or keeps every row of a result set.
  • A leak through a static map, a ThreadLocal, or a listener that is never removed.

Quick answer: capture a heap dump at the moment of failure, size the heap against the container limit, then fix the code path that retains more than it needs.

Core Mechanics, Signatures & Reproducible Setup

The heap is bounded by -Xmx, or in container-aware JVMs by a percentage of the container memory limit. When a full GC cannot free enough contiguous space for the requested allocation, the JVM throws OutOfMemoryError and, if configured, writes a heap dump.

java
// repro: hold every row in memory, compile with javac, run with a small heap import java.util.ArrayList; import java.util.List; public class HeapRepro { record Row(int id, String payload) {} public static void main(String[] args) { List<Row> rows = new ArrayList<>(); for (int i = 0; ; i++) { rows.add(new Row(i, "x".repeat(1024))); if (i % 100_000 == 0) System.out.println("rows=" + i); } } }
bash
javac HeapRepro.java java -Xmx256m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp HeapRepro # rows=1200000 # java.lang.OutOfMemoryError: Java heap space # Dumping heap to /tmp/java_pid*.hprof ...

The message variants point at different memory areas, and the fix differs for each:

MessageAreaTypical cause
Java heap spaceheaplive set larger than -Xmx
GC overhead limit exceededheap98% of time in GC with almost no reclaim
Metaspaceclass metadatadynamic class generation, redeploy leaks
Compressed class spaceclass metadatatoo many classes for the reserved space
Direct buffer memoryoff-heapNetty, NIO buffers not released
unable to create native threadthreadsthread per request without a pool

Key Comparison Table

Sizing approachFlagBehaviour
Fixed heap-Xmx2gpredictable, ignores container size
Percentage of container memory-XX:MaxRAMPercentage=75adapts to the limit, safe default
Fixed heap with preallocation-Xms2g -Xmx2gno resize pauses, slower start
Container support defaultnone25% of the limit on Java 10 and later

Diagnostic tools and what each answers:

ToolQuestion answeredCost at runtime
jcmd <pid> GC.heap_infohow full is the heap nowlow
-XX:+HeapDumpOnOutOfMemoryErrorwhat was alive at failurenothing until failure
jcmd <pid> GC.class_histogramwhich classes dominatemedium pause
jmap -dump:live,format=b,file=x.hproffull object graphhigh pause
GC logs (-Xlog:gc*)is the heap actually full or just slowlow
JFR recordingallocation sites, lock contentionlow

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Always capture a dump before the process exits

Without a dump, the only evidence left is a stack trace at the allocation site, which is the wrong place to look. Enable the flags in the startup command or the container entrypoint.

bash
java -XX:+HeapDumpOnOutOfMemoryError \ -XX:HeapDumpPath=/var/dumps \ -XX:+ExitOnOutOfMemoryError \ -Xlog:gc*:file=/var/log/gc.log:time,uptime:filecount=5,filesize=20M \ -jar app.jar

Mount /var/dumps as a volume; a dump written inside a container filesystem disappears with the container. ExitOnOutOfMemoryError makes the process exit so an orchestrator restarts it, instead of continuing in a broken state.

2. Read the dominator tree, not the biggest class

A histogram shows byte[] and String at the top in almost every dump. The useful question is which object holds them.

bash
jcmd 1 GC.class_histogram | head -20 # open the .hprof in Eclipse MAT, then: # Leak Suspects -> Dominator Tree -> Path to GC Roots (exclude weak references)

In MAT, sort the dominator tree by retained heap. A single ReportCache or HashMap holding most of the heap is the usual answer, and its retained size is what a fix must reduce.

3. Size the heap against the container, not the host

A JVM that thinks it is on a 64 GB host will set a 16 GB default maximum and get killed by the container limit long before it throws this error.

# Kubernetes: leave headroom for metaspace, stacks, and off-heap resources: limits: memory: 2Gi env: - name: JAVA_TOOL_OPTIONS value: "-XX:MaxRAMPercentage=75 -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dumps"
bash
java -XX:+PrintFlagsFinal -version | grep -E 'MaxHeapSize|MaxRAMPercentage' # size_t MaxHeapSize = 1610612736 -> about 75% of 2 GiB

The remaining 25% is not waste: metaspace, thread stacks, direct buffers, and the JVM's own structures live outside the heap. Setting MaxRAMPercentage=100 converts a heap error into an OOM-kill (exit 137) with no Java trace at all.

4. Bound the code path that retains data

Most heap errors come from a query or loop with no upper bound. Stream, paginate, and cap.

java
// before: one list of every row List<ReportRow> rows = repository.findAll(); // after: page through with a fixed batch size int page = 0; while (true) { List<ReportRow> batch = repository.findPage(page++, 500); if (batch.isEmpty()) break; writer.write(batch); batch.clear(); }
java
// caches need a size and an expiry Cache<String, Report> cache = Caffeine.newBuilder() .maximumSize(10_000) .expireAfterWrite(Duration.ofMinutes(10)) .build();

A result set with a cursor or a Stream still reads from the database, but the retained objects stay bounded by the batch size rather than the table size.

5. Tell heap exhaustion from GC overhead and native limits

GC overhead limit exceeded is a policy decision by the collector: it spent too long collecting and reclaimed almost nothing. The heap may be full of long-lived objects, or the heap may be too small for the live set by a small margin.

bash
# is the heap full or is the collector thrashing? grep -E "Pause Full|to-space exhausted" gc.log | tail -20 jcmd 1 GC.heap_info

If the logs show a full GC with most of the heap still live, raise the limit or fix the retention. If they show repeated collections that reclaim almost nothing and the heap is well below -Xmx, the live set is smaller than the heap and the collector's ergonomics need attention, such as a different collector or a larger young generation.

Common Compilation/Runtime Mistakes & Version Gotchas

Adding memory as the fix. Raising -Xmx buys time and hides a leak. Do it only after a dump shows the live set is legitimately large, and record the number you set and why.

Catching OutOfMemoryError. It is an Error, not an Exception, and catching it leaves the heap in a state where nothing is reliable. Let it propagate, exit, and restart.

Leaking through static collections. A static Map keyed by tenant id, a ThreadLocal on a pooled thread, or a listener registered per request retains everything it touches until the process restarts. In a dump these show as one entry with a huge retained size.

Heap limits set in the Dockerfile. JAVA_OPTS baked into the image silently overrides the orchestrator's sizing. Keep JVM flags in the deployment configuration so they can be changed without a rebuild.

Version differences worth knowing. Java 10 and later respect container limits by default (UseContainerSupport), so -Xmx computed from the host is at best redundant and at worst too large. Java 21 offers the generational ZGC (-XX:+UseZGC -XX:+ZGenerational), which changes pause behavior but not the live-set math; a heap error still means the live set does not fit. -XX:+ExitOnOutOfMemoryError has existed since Java 8 but behaves differently with some wrappers, so confirm the process actually exits in your base image.

Where to look after a restart. When the OOM kills the pod, the previous container logs hold the stack and the dump path. Correlate the failure minute from the timestamp conversion tool with the deployment or traffic change, and check whether the error is a 137 kill in the status codes sense rather than a Java exception; the two need different fixes.

Reference material: java command and Troubleshooting memory leaks.

Official references

primary documentation

The Java documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.