Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A service throws OutOfMemoryError with different messages on different days: "Java heap space", "Metaspace", "unable to create native thread", and "Direct buffer memory". What does each indicate and how do you investigate?

Each message names a different memory area. "Java heap space" means the heap is full of live objects; "Metaspace" means too much class metadata, usually a class loader leak or runaway class generation; "unable to create native thread" means the operating system or container refused another thread; and "Direct buffer memory" means off-heap NIO buffers reached -XX:MaxDirectMemorySize. A related message, "GC overhead limit exceeded", means the JVM spent most of its time collecting garbage while recovering almost nothing. Each needs a different investigation, from heap dumps to thread dumps to native memory tracking.

Why this question is asked

OutOfMemoryError sounds like one problem, but the JVM manages several separate memory areas, and each can run out for its own reasons. A team that answers every OOM by raising -Xmx will fix one of these messages at best and make others worse, because a bigger heap leaves less room in the container for everything else. Interviewers ask this to see whether we can read the message and go straight to the right tool. In this answer, we will recap the JVM's memory areas, take each message in turn with its causes and investigation, look at GC overhead, and finish with why running on after an OOM is unsafe.

1A Quick Recap of the JVM's Memory Areas

A Java process uses much more than the heap. The heap holds our objects and is limited by -Xmx. Metaspace holds class metadata, the internal description of every loaded class, and lives in native memory, limited only by -XX:MaxMetaspaceSize if we set it. Each platform thread has a native stack, by default about 1 MB. Direct buffers, created by ByteBuffer.allocateDirect and used heavily by NIO and Netty, live outside the heap and are capped by -XX:MaxDirectMemorySize, which defaults to roughly the maximum heap size. On top of these come the JIT's code cache, GC data structures and native libraries.

When any of these areas cannot grow, the JVM throws OutOfMemoryError with a message naming the area. So the message is the first and most important clue.

Reading the OutOfMemoryError message
MessageAreaTypical causeFirst tool
Java heap spaceheap (-Xmx)leak or too much live dataheap dump
Metaspaceclass metadataclass loader leak, generated classesclass histogram, loader stats
unable to create native threadOS threads / memorythread leak, pid or memory limitthread dump, thread count
Direct buffer memoryoff-heap NIO buffersbuffer leak, unpooled buffersBufferPool metrics, NMT
GC overhead limit exceededheap, Parallel GCheap almost full of live dataheap dump, GC logs
The message names the area that ran out; each area needs a different investigation.

2"Java heap space"

This means the garbage collector could not find room for a new object even after a full collection, so the heap is full of objects that are still reachable. Either we have a leak, objects kept alive by mistake, such as an unbounded cache or a static map that only grows, or the workload genuinely needs more memory, such as loading a 2 GB report into a list.

The tool is a heap dump, a snapshot of every object on the heap. We configure the JVM to write one automatically at the moment of failure, then open it in Eclipse MAT, VisualVM or a similar analyser and look at retained size, the memory that would be freed if an object were collected. The dominator tree usually points straight at the culprit, for example one ConcurrentHashMap retaining 1.6 GB of a 2 GB heap.

Shell
java -Xmx2g \
-XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=/dumps \
-Xlog:gc*:file=/logs/gc.log:time,uptime \
-jar app.jar
# On failure: java.lang.OutOfMemoryError: Java heap space
# Dumping heap to /dumps/java_pid1.hprof ...
# Quick check on a live process:
jcmd 1 GC.class_histogram | head -15 # top classes by instance count and bytes

GC logs separate the two cases: a leak shows the heap after each collection climbing for hours, a spike shows a sudden jump.

3"Metaspace"

This means too much class metadata. Applications load a fixed number of classes at startup, so steady growth points to classes being created continuously or never unloaded. Classes are unloaded only when their class loader becomes unreachable, so the usual cause is a class loader leak: in an application server, a redeployed application whose old class loader is still referenced by a thread, a ThreadLocal or a JDBC driver registration, so each redeploy adds another copy of every class. The other cause is runaway class generation: dynamic proxies, CGLIB or ByteBuddy subclasses, scripting engines or serializers that generate a new class per call instead of caching it.

We investigate with jcmd's VM.metaspace and VM.classloader_stats commands, or a class histogram over time, looking for a growing number of classes with generated names such as $$SpringCGLIB$$ or Proxy followed by numbers, or many loaders of the same type. A heap dump also shows class loader objects and what keeps them alive.

4"unable to create native thread"

This message does not mean the heap is full. It means the JVM asked the operating system for a new thread and was refused. Inside a container, the limits are usually the process or thread count limit, such as the pids limit of the cgroup, or the container's memory limit, since each thread needs native memory for its stack. Outside containers, ulimit -u on Linux plays the same role.

The cause is almost always a thread leak, such as an executor created per request and never shut down. We take a thread dump with jcmd <pid> Thread.print and group threads by name; the jvm.threads.live metric shows the leak growing long before the failure.

Shell
jcmd 1 Thread.print > threads.txt
grep -o '^"[a-zA-Z-]*' threads.txt | sort | uniq -c | sort -rn | head -5
# 3912 "pool-
# 40 "http-nio-8080-exec-
# 12 "kafka-producer-network-thread
# 3,912 threads from unnamed executors: an executor is being created and never shut down

5"Direct buffer memory"

Direct buffers are memory outside the heap that NIO can hand to the operating system without copying, which is why networking libraries like Netty use them. Their total is capped by -XX:MaxDirectMemorySize. When an allocation would exceed the cap, the JVM throws this error. Direct buffers are freed only when their small heap object is garbage collected, or explicitly by a pooling library, so a leak of pooled buffers or a burst of very large allocations can exhaust the cap while the heap looks healthy.

We watch the direct pool through the jvm.buffer.memory.used metric with id=direct, use Native Memory Tracking (-XX:NativeMemoryTracking=summary, then jcmd <pid> VM.native_memory summary), and in a test environment turn on Netty's leak detector, which reports where unreleased buffers were allocated.

6"GC overhead limit exceeded" and Why Not to Run On

This message is a heap problem in disguise. With the Parallel collector, the JVM throws it when it spends more than about 98 percent of its time in garbage collection and recovers less than about 2 percent of the heap. The heap is not quite full, but it is so nearly full of live objects that the application has effectively stopped making progress. It is investigated like Java heap space, with a heap dump. G1, the default collector in most configurations, does not use this check (check your collector), so the same situation there eventually ends in Java heap space after long GC pauses.

Whatever the message, continuing after an OutOfMemoryError is usually unsafe. The error is thrown in whichever thread happened to request memory, at any line, so a thread may have died halfway through an update, a lock may be held by code that never reached its finally block, and a background thread that a library relies on, such as a connection pool's housekeeper, may be gone. The process looks alive, passes a simple health check, and serves wrong or stuck responses. That is why the usual policy is to exit with -XX:+ExitOnOutOfMemoryError and let the orchestrator restart the process, after the heap dump has been written.

7Follow-up questions

Why is it usually unsafe to keep running after an OutOfMemoryError?

Because the error can hit any thread in the middle of any operation. Data structures may be half-updated, locks may be held forever, and important background threads may have died silently. The JVM keeps running, but its state can no longer be trusted, so it is safer to capture diagnostics, exit, and let a fresh process take over.

Will raising -Xmx fix unable to create native thread?

No, and it may make it worse. In a container with a fixed memory limit, a bigger heap leaves less native memory for thread stacks, metaspace and direct buffers. The fix is to find and stop the thread leak, or to raise the process limit if the thread count is genuinely needed.

8Conclusion

In this answer, we saw that each OutOfMemoryError message names a different area. Java heap space means live objects fill the heap and calls for a heap dump; Metaspace points to class loader leaks or generated classes; unable to create native thread means OS or container thread or memory limits and calls for thread dumps; Direct buffer memory means off-heap NIO buffers hit their cap and calls for buffer metrics and native memory tracking. GC overhead limit exceeded means the JVM was collecting constantly for almost no gain. Because the JVM state is unreliable after an OOM, the usual policy is to dump, exit and restart.

What to say in the interviewAbout 100 seconds aloud

Open with

The message tells me which memory area ran out, so I start there. Java heap space means the heap is full of live objects even after a full GC, either a leak like an unbounded cache or a genuinely large workload.

Then, if they want more

I run with HeapDumpOnOutOfMemoryError and a HeapDumpPath, open the dump in Eclipse MAT, and look at the dominator tree and retained sizes, and I use GC logs to see whether the post-GC baseline climbs over time.

Metaspace means too much class metadata, which usually means a class loader leak after redeploys, or proxies and generated classes created per call instead of cached; I check class counts and class loader stats with jcmd.

Unable to create native thread is not a heap problem: the OS or container refused a new thread, because of a pids or memory limit, so I take a thread dump, group threads by name, and usually find an executor being created and never shut down.

Direct buffer memory means NIO off-heap buffers hit MaxDirectMemorySize, so I look at the direct buffer pool metric, native memory tracking, and Netty's leak detector. GC overhead limit exceeded means the JVM spent most of its time in GC recovering almost nothing, which I treat like a heap problem.

And after any OOM, I would not keep the process running, because threads may have died and locks may be held; I would exit and let the orchestrator restart it.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A service throws OutOfMemoryError with different messages on different days: "Java heap...": https://scrivio-interview-library.netlify.app/java/exceptions/f941170542/