JVM runtime memory areas, OOM types, and container sizing
A map of HotSpot JVM heap and native memory areas, how to diagnose each OutOfMemoryError type with NMT, and how to size container heaps safely.
Setting an 800MB heap inside a 1GB Docker container often ends in
OOMKilled (137)with no Java exception in the logs because of native memory outside the heap. This post maps HotSpot JVM memory areas, breaks down eachOutOfMemoryErrortype with NMT commands, and explains how to size container heaps safely.
Tested with Java 21 LTS (Eclipse Temurin / OpenJDK HotSpot JVM) on Linux cgroup v2 / Docker.
Map of HotSpot JVM runtime memory
HotSpot divides memory into the garbage-collected Heap and Non-Heap / Native areas allocated directly from the OS. Inside the heap, new objects land in the Young Generation (Eden plus Survivor spaces S0 and S1), and objects that survive multiple GC cycles get promoted to the Old Generation.
Outside the heap, several native regions consume physical RAM: Metaspace stores class metadata, Thread Stacks hold per-thread call frames, CodeCache caches JIT-compiled native machine code, Direct ByteBuffers back NIO and Netty off-heap I/O, and GC internals (Card Tables, Remembered Sets, and region metadata) add their own footprint.
flowchart TD
RSS["Total Container RSS (cgroup v2 limit)"] --> HEAP["Heap (Eden / S0 / S1 / Old)"]
RSS --> META["Metaspace (class metadata)"]
RSS --> STACK["Thread Stacks (threads x Xss)"]
RSS --> DIRECT["CodeCache & Direct ByteBuffers"]
RSS --> NATIVE["GC internals & JVM native"]
Why an 800MB heap triggers OOMKilled in a 1GB container
In production, giving a 1GB container -Xmx800m frequently results in the process dying under load with Exit Code 137 (OOMKilled) and zero Java error logs. The JVM only throws OutOfMemoryError when an internal region crosses its own limit. Linux’s OOM Killer, on the other hand, enforces the cgroup v2 limit (memory.max) against the process’s total RSS.
Total RSS ≈ Heap + Metaspace + (Thread Stack × Thread Count) + CodeCache + Direct ByteBuffer + GC & native overhead
Suppose a Spring Boot app fills its 800MB heap while holding 120MB in Metaspace, 60MB of committed stacks across 150 threads, 80MB in CodeCache, 64MB in Direct Buffers, and 80MB in G1GC internal structures. Total RSS crosses 1,200MB. Even if the heap still has a few megabytes free, the moment RSS hits the 1,024MB container cap, the kernel sends SIGKILL (9) and terminates the JVM immediately (128 + 9 = 137).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
{
"type": "doughnut",
"data": {
"labels": [
"Heap (800MB)",
"Metaspace (120MB)",
"CodeCache (80MB)",
"G1GC Overhead (80MB)",
"Direct Buffer (64MB)",
"Thread Stacks (60MB)"
],
"datasets": [
{
"label": "Memory Footprint (MB)",
"data": [800, 120, 80, 80, 64, 60]
}
]
},
"options": {
"plugins": {
"title": {
"display": true,
"text": "1,204MB total RSS breakdown with -Xmx800m in a 1GB container"
}
}
}
}
Diagnosing OutOfMemoryError types with NMT
Unlike a silent kernel OOMKill, breaching a JVM-managed limit raises an OutOfMemoryError with a specific detail message that points you to the right area.
| OOM message | Memory area | Common cause | First step |
|---|---|---|---|
Java heap space | Heap | Collection leak, huge query, undersized heap | Analyze heap dump, tune -Xmx |
Metaspace | Native (Metaspace) | Dynamic proxy churn, classloader leak | Audit proxies/loaders, set MaxMetaspaceSize |
Direct buffer memory | Direct Buffer | Unreleased Netty/NIO buffers or low cap | Check release(), tune MaxDirectMemorySize |
unable to create native thread | OS threads | Unbounded pools, OS memory or nproc cap | Cap thread pools, lower -Xss, or scale up |
GC overhead limit exceeded | Heap / GC | Over 98% time in GC reclaiming under 2% | Profile allocations/leaks, resize heap |
To tell whether growth comes from the heap or native memory, boot the JVM with -XX:NativeMemoryTracking=summary and measure actual committed bytes per region using jcmd:
1
2
3
4
5
6
7
8
9
10
11
12
13
# 1. Start JVM with NMT and automatic heap dump on OOM
java -XX:NativeMemoryTracking=summary \
-XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=/var/log/jvm/heapdump.hprof \
-jar app.jar
# 2. Inspect reserved/committed memory per area and diff over time
jcmd <pid> VM.native_memory summary scale=MB
jcmd <pid> VM.native_memory baseline
jcmd <pid> VM.native_memory summary.diff scale=MB
# 3. Capture a live heap dump manually (triggers STW; drain traffic first)
jmap -dump:live,format=b,file=/tmp/live-heap.hprof <pid>
Sizing JVM heaps in Docker containers
Java 21 enables -XX:+UseContainerSupport by default, so the JVM reads cgroup v2 memory limits automatically. Choosing between percentage flags like -XX:MaxRAMPercentage=70.0 and fixed -Xms/-Xmx values comes down to container size.
Percentages adapt automatically when you resize a container, but on a small container (1GB or less), the remaining 30% (300MB) is often too tight for Spring Boot’s non-heap footprint. On 4GB+ containers, non-heap overhead makes up a smaller share, so 70–75% works well. In practice, I subtract the fixed non-heap baseline first (350–512MB for a typical Spring Boot service) and assign the remainder to the heap. Start around 512MB on a 1GB container, 60–65% (~1.2GB) on a 2GB container, and 70% on 4GB+ containers, then refine those numbers against real NMT readings.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Dockerfile (Eclipse Temurin Java 21 / recommended baseline for a 2GB container)
FROM eclipse-temurin:21-jre-jammy
WORKDIR /app
COPY build/libs/app.jar app.jar
ENV JAVA_OPTS="\
-XX:InitialRAMPercentage=65.0 \
-XX:MaxRAMPercentage=65.0 \
-XX:MaxMetaspaceSize=256m \
-XX:MaxDirectMemorySize=128m \
-XX:ReservedCodeCacheSize=128m \
-XX:NativeMemoryTracking=summary \
-XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=/var/log/jvm/heapdump.hprof \
-XX:+ExitOnOutOfMemoryError"
ENTRYPOINT ["sh", "-c", "exec java $JAVA_OPTS -jar /app/app.jar"]
Setting explicit caps on MaxMetaspaceSize and MaxDirectMemorySize ensures the JVM logs a clear OutOfMemoryError and exits cleanly instead of getting silently killed by the kernel OOM Killer.
Common memory pitfalls in production
Leaving initial heap size unpinned or omitting a Direct Memory cap makes a container look healthy at idle and crash with
OOMKilledright at peak traffic.
First, not matching initial and maximum heap (-Xms or InitialRAMPercentage) forces heap resizing and page faults during traffic spikes, adding tail latency right when load climbs. Worse, you won’t discover that your memory budget is overcommitted until peak traffic hits. For single-purpose containers, pinning initial and max heap to the same value surfaces sizing mistakes at startup.
Second, Direct Memory leaks in Netty and NIO stacks. In Spring WebFlux, Lettuce, or gRPC apps, forgetting to release a ByteBuf—or long GC intervals delaying Cleaner reclamation—lets RSS climb while heap graphs stay flat. If you omit -XX:MaxDirectMemorySize, HotSpot defaults it to -Xmx, which can double your memory usage and blow past the container limit fast.
Reliable container memory tuning isn’t guesswork: measure your real RSS breakdown with NMT, cap non-heap regions explicitly, and budget the heap from what’s left.
- Did you subtract non-heap overhead (350–512MB baseline) before picking
-XmxorMaxRAMPercentage? - Are
InitialRAMPercentageandMaxRAMPercentageset to the same value in dedicated containers? - Are
MaxMetaspaceSize,MaxDirectMemorySize, andReservedCodeCacheSizeexplicitly capped? - Have you enabled
-XX:NativeMemoryTracking=summaryand verified actualcommittedmemory under load? - Are
-XX:+HeapDumpOnOutOfMemoryErrorand-XX:+ExitOnOutOfMemoryErrorconfigured so OOM failures leave evidence and trigger clean restarts?