Java Heap Size Container Settings From Real Numbers
Size the Java heap in a container from measured numbers: live set after GC, non heap memory, the container limit and MaxRAMPercentage.

"Set the heap to 75 percent of the container" is advice that works for some services and kills others, because it treats the heap as the memory of the process, and it is not. A JVM in a 2 GiB container with a 1.5 GiB heap has 512 MiB left for everything else: metaspace, thread stacks, the code cache, garbage collector structures, direct buffers and the C libraries. If that is not enough, the kernel ends the container with exit code 137 and no Java stack trace. The way out is arithmetic from numbers you measure on your own service, not a percentage from a blog. This post lists the numbers to collect, works a full example for a service in a 2 GiB container, shows how MaxRAMPercentage follows from the result, lists the pitfalls, verifies the choice in production and explains why a heap that is too big can hurt. Commands use JDK 25; the figures in the worked example are an illustrative service, and you should replace them with your own measurements.
The numbers to collect
The process's memory is the sum of areas, and each can be measured on a running JVM with Native Memory Tracking. Start the service with tracking on, in a staging environment under realistic load:
java -XX:NativeMemoryTracking=summary -Xmx1g -jar app.jar &
jcmd $! VM.native_memory summaryTotal: reserved=2410MB, committed=1368MB
- Java Heap (reserved=1024MB, committed=1024MB)
- Class (reserved=1081MB, committed=96MB)
- Thread (reserved=262MB, committed=262MB)
- Code (reserved=248MB, committed=71MB)
- GC (reserved=61MB, committed=61MB)
- Internal (reserved=48MB, committed=48MB)
- Other (reserved=34MB, committed=34MB)Read committed, the memory actually in use, not reserved. The areas, and how to think about each:
| Area | What it holds | Scales with |
|---|---|---|
| Java Heap | Your objects | Data volume, cache sizes, concurrency |
| Class (metaspace) | Class metadata | Number of classes loaded: frameworks, proxies |
| Thread | Stacks | Number of platform threads x stack size (about 1 MiB each) |
| Code | JIT-compiled code | Hot code size; capped by ReservedCodeCacheSize |
| GC | Collector bookkeeping | Heap size (remembered sets, mark bitmaps) |
| Internal and Other | Direct buffers, symbols, NIO | Netty, large buffers, JNI |
Collect two values for each non-heap area: the committed size at idle and after load. The non-heap total is what the heap must leave room for. The details of each area are in JVM memory areas. Also measure the heap itself: the live set after a full collection (what the application truly needs), not the peak. A peak after a collection of 400 MiB means a heap of 1 GiB leaves comfortable headroom, and a live set of 900 MiB means it does not.
Worked example
A Spring Boot service in a container with a 2 GiB limit. Measurements under load, from the tracking output and the GC log:
| Item | Measured |
|---|---|
| Live set after full GC | 410 MiB |
| Metaspace (committed) | 96 MiB |
| Thread stacks (200 threads x about 1 MiB) | 200 MiB |
| Code cache | 71 MiB |
| GC structures | 61 MiB |
| Internal, direct buffers, other | 82 MiB |
| Safety margin for the kernel and bursts, 10 percent of the limit | 205 MiB |
Non-heap total: 96 + 200 + 71 + 61 + 82 = 510 MiB. Add the safety margin: 715 MiB. The heap is the limit minus that: 2048 minus 715 is 1333 MiB, so -Xmx1280m with some slack, or as a percentage, 1280 / 2048 = 62.5 percent. The live set of 410 MiB is far below the 1280 MiB heap, so the collector has room to work and the heap is not the constraint.
Now the same service in a 512 MiB container, to see why a percentage is a trap. The non-heap areas barely shrink: metaspace and the code cache are about the same, and 200 platform threads still need their stacks (reduce the thread count, or the stack with -Xss512k). Say after tuning, non-heap is 380 MiB, margin 50 MiB (10 percent). The heap is 512 minus 380 minus 50 = 82 MiB, far below the 410 MiB live set. No heap setting makes this fit: the container is too small for the service, whatever the percentage. The honest answer from the arithmetic is "this service needs at least about 1 GiB", and a flag cannot buy back the difference. That is the value of doing the calculation: it tells you when the answer is a bigger container, not a smaller heap.
Two sizes, two different percentages (62.5 and 16), which is why one global number cannot be right.
MaxRAMPercentage
Once you know the heap for a given container size, express it as a percentage so the same image works across sizes. The flag takes the share of the container limit that the JVM reads from the cgroup:
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=62", "-jar", "app.jar"]Verify what the JVM computed, instead of trusting the arithmetic:
docker run --rm --memory=2g eclipse-temurin:25-jre \
java -XX:MaxRAMPercentage=62 -XX:+PrintFlagsFinal -version | grep MaxHeapSize size_t MaxHeapSize = 1330642944 {product} {command line}1,330,642,944 bytes is 1269 MiB (62 percent of 2048 is 1269.76). The flag, its defaults (25 percent) and the interaction with -Xmx, which overrides it, are covered in MaxRAMPercentage and container awareness, and the flag reference is the java command documentation. If the service will run in containers of several sizes, compute the percentage for the smallest size you support, or choose a percentage that grows with the limit: the fixed non-heap overhead means the right share is lower for small containers and higher for large ones. A reasonable pair: 50 percent below 1 GiB, 65 to 75 percent above 4 GiB, and your measured value in between.
Pitfalls
Counting only the heap. The most common mistake, and the cause of OOMKilled with a healthy-looking heap graph. See the diagnosis in a Java container killed by the OOM killer.
Thread count. 500 threads with the default 1 MiB stack is 500 MiB outside the heap. A service with a big thread pool or many connection handlers needs a lower heap percentage, or a smaller stack, or virtual threads.
Direct memory. Netty, NIO channels and some database drivers allocate off-heap buffers. The default limit equals the heap size (MaxDirectMemorySize), so the process can use twice the heap. Set it deliberately when you use them: -XX:MaxDirectMemorySize=256m.
Metaspace without a cap. It grows with loaded classes, including generated proxies. A leak (redeploys, dynamic class generation) grows it without bound and takes the container with it. Set -XX:MaxMetaspaceSize=256m so a leak fails as a Java OutOfMemoryError: Metaspace with a stack trace rather than a silent kill.
**Setting -Xms equal to -Xmx in a tight container.** It commits the whole heap at startup, which is fine when you have sized it and wasteful when you have not; the process's resident size jumps to the maximum immediately.
Forgetting the limit is per container, not per JVM. A sidecar, an agent or a second JVM in the same container shares the limit.
Trusting the node. Kubernetes requests affect scheduling and limits affect killing. The JVM sizes itself from the limit. A limit far above the request lets you use memory the scheduler did not reserve, and a node under pressure kills you first.
Verify in production
Check the choice against real behavior, not the staging run. Watch these over several days, including a peak:
- Container memory working set (
container_memory_working_set_bytes) against the limit. A margin of at least 10 percent at the peak. - Heap after full GC, the live set: it should be flat or slowly varying, and well under the max heap. A heap that sits near its maximum after collection is undersized.
- GC time and pause percentiles. A collector that runs constantly because the heap is tight shows up as latency.
- **Restarts with reason
OOMKilled.** Zero. - **Non-heap via the
jvm.memory.usedmetric** taggedarea=nonheap, compared with your measured 510 MiB.
Export native memory data periodically in a lower environment as a sanity check, since a slow off-heap leak is invisible to heap monitoring. If you see OOMKilled after the change, read the container's last state and compare the total against the sum of your measured parts; the missing piece is usually threads or direct buffers, covered in native memory tracking and off-heap leaks and the Java troubleshooting guide on native memory.
Heap too big can hurt
More heap is not free. A larger heap means longer concurrent mark cycles and, with some collectors, longer pauses; the pause behavior depends on the collector, and the choice is in G1 versus ZGC versus Shenandoah. It also means bigger GC bookkeeping (the GC row in the table above grows with the heap), a larger resident set, slower startup when pretouching and, in a container, a higher chance of tripping the limit. A service whose live set is 410 MiB and which runs well with a 1 GiB heap gains nothing from 1.5 GiB except risk. Size for the live set times a factor of 2 to 3 for the collector's working room, then stop. For heap-exhaustion errors, the diagnosis starts with whether it is a leak or a sizing problem: OutOfMemoryError: Java heap space.
Where this does not apply
On a bare-metal or VM host that runs only your JVM, there is no cgroup limit; size the heap against the machine's RAM minus the operating system's needs. For short-lived jobs and native images, the memory profile is different (native images have no JIT or metaspace to budget), and you measure the resident size directly. And if you cannot run Native Memory Tracking, a cruder method works: run under load, read the container's peak working set, subtract the heap's peak and call the remainder your non-heap need.


