Video in progress
If the container limit is 1 GB, why is setting -Xmx1g a mistake?
-Xmx limits only the heap, but beyond the heap the JVM also takes memory for Metaspace, thread stacks, the code cache, GC structures and direct buffers. The total exceeds 1 GB and the Linux OOM killer kills the container with exit 137.
📖 Answer
In this case Java throws no OutOfMemoryError at all. The container just dies, there is nothing in the log, and in Kubernetes you see the OOMKilled state and restarts. That is why it is hard to find.
A rough calculation for a 1 GB container:
- heap: the value you set;
- Metaspace: 80-200 MB;
- thread stacks: 200 threads x 1 MB (virtual memory; real usage is lower);
- code cache: 50-240 MB;
- the GC's internal structures, direct buffers (Netty), native libraries.
Practical advice: set the heap as a percentage of the limit:
java -XX:MaxRAMPercentage=70.0 -jar app.jar
Java 10+ (and 8u191+) sees the container limit by itself, so the percentage is calculated correctly, and if the pod limit changes you don't need to update the flag. The default MaxRAMPercentage is 25%, which is usually too little for a server.
To see the real memory breakdown, start with -XX:NativeMemoryTracking=summary and run jcmd <pid> VM.native_memory summary.
Sign up to mark studied questions and save your progress.