Fix java.lang.OutOfMemoryError Java Heap Space Errors
Fix java.lang.OutOfMemoryError Java heap space by deciding whether the heap is too small or something is leaking, using a heap dump to tell the two apart.

The process dies, or one request fails, with this line:
Exception in thread "http-nio-8080-exec-7" java.lang.OutOfMemoryError: Java heap spaceThe garbage collector tried to make room, could not, and an allocation failed. The heap holds more reachable objects than its maximum size allows. The message says nothing about how much memory the machine has left, and nothing about whether the cause is a leak or just a heap set too small. Telling those two apart is the whole job, and the only reliable tool is a heap dump. Neighbouring messages point at other memory areas: GC overhead limit exceeded and Metaspace have different fixes.
Capture the evidence first
Do not change the heap size before you have a dump. Ask the JVM to write one when it fails:
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/dumps -Xmx1gA dump is about as large as the heap was, so give the path a volume with room for it. In a container, mount a volume there, since a dump written to the container filesystem disappears when the pod restarts. If you want the orchestrator to replace the instance as soon as it fails, add -XX:+ExitOnOutOfMemoryError. A process that stays up after an OutOfMemoryError is often half broken, because other threads are failing at the same moment.
For a process that is still running but swelling, take a dump on demand:
jcmd <pid> GC.heap_dump /var/dumps/heap.hprofThe call pauses the application while it writes, so the cost in production is real; using jcmd safely explains how to limit it. The capture and analysis workflow in detail is in heap dumps with Eclipse MAT.
Leak or too small?
Before opening the dump, look at the GC log. Turn it on with -Xlog:gc*:file=/var/log/gc.log. Compare the heap occupancy right after each full or mixed collection. If that floor is flat, the live set is stable and the heap is too small for it. If the floor climbs steadily across hours, something is accumulating, and a bigger heap only delays the failure. Four hours to the failure at 1 GB means roughly eight hours at 2 GB, which is a postponement and not a fix.
Read the dump
Open the file in Eclipse MAT or the heap viewer in VisualVM, and look at the dominator tree. The top entry is the object whose removal would free the most memory. Ask two questions of it: what type is filling the heap, and what keeps it reachable. The command to answer the second is "path to GC roots, excluding weak references". The chain usually ends in one of four places.
| Holder at the end of the path | Typical cause |
|---|---|
A static map or list | A cache or registry that only grows |
A ThreadLocal on a pooled thread | Request data kept for the life of a worker |
| A listener or callback list | Registered and never removed |
| A collection held by a method | A query or file read in full instead of streamed |
Fix a leak at its source
The most common one is a cache with no bound:
private static final Map<String, Report> CACHE = new HashMap<>(); // grows foreverGive it a maximum size and an expiry. With Caffeine that is three lines:
private static final Cache<String, Report> CACHE = Caffeine.newBuilder()
.maximumSize(10_000)
.expireAfterWrite(Duration.ofMinutes(30))
.build();The ThreadLocal case is quieter. A web server reuses its worker threads, so a value stored in a ThreadLocal and never removed stays in memory for as long as the thread lives, which is until shutdown. Clear it in a finally block:
private static final ThreadLocal<RequestContext> CONTEXT = new ThreadLocal<>();
void handle(Request request) {
CONTEXT.set(RequestContext.from(request));
try {
process(request);
} finally {
CONTEXT.remove();
}
}For large results, stop loading everything. Read pages, or stream rows with a cursor, as in reading large result sets. A request that puts two million rows into a List fails at any heap size you can afford, and the fix is to change the shape of the work.
When the data really is that big
Sometimes the dump shows a healthy structure that is large, such as a lookup table that must be in memory. Then the heap needs to be larger. Size it from measurements: take the live set after a full collection, then add headroom so collections are not constant, commonly a live set at half the heap or less. Setting -Xmx equal to the container's memory limit invites a different failure, because the heap is not the only memory the process uses; the arithmetic is in sizing the heap in a container.
A worked reading of a dump
Suppose the dominator tree shows one ConcurrentHashMap retaining 640 MB of a 1 GB heap, and its entries are Session objects. Follow the path to the GC roots: the map is a static field in a class named SessionRegistry. Now read the code for that class. If sessions are added on login and the only removal is an explicit logout call, every user who closes the browser without logging out leaves an entry behind, and the map grows by the number of such users per day. That is a leak with a name, a cause and a fix: add an expiry, or tie removal to the session timeout event. The same dump read with the other question, what is large, would have said "sessions", which is true and useless. The path to the roots is what turns a type name into a line of code.
If instead the largest holder is a byte[] referenced by a single request thread, the story is different. One request is loading a big file or response body into memory. No registry is leaking, and the fix is streaming. Two dumps of the same application can point in opposite directions, which is why guessing from the stack trace of the failing thread is unreliable: the thread that hits the limit is just the one that asked for memory last.
Mistakes that look like this error
Memory pressure in a container can be the kernel killing the process, which gives no Java exception at all and is covered in OOMKilled. Catching OutOfMemoryError and carrying on is not a recovery strategy, since the state of the program after it is unknown. If the error names unable to create native thread or Direct buffer memory, the heap is not the problem and the dump will show nothing; look at thread counts or native memory tracking. The flags are documented in the [java command reference](https://docs.oracle.com/en/java/javase/25/docs/specs/man/java.html), and the troubleshooting guide covers the diagnostic tools.


