Video in progress
A Java app in a container gets OOMKilled from time to time, but the heap metrics are well below `-Xmx`. Where do you look?
OOMKilled is not the JVM's OutOfMemoryError; it is the cgroup limit, which counts the whole RSS of the process. Besides the heap, metaspace, thread stacks, direct buffers, the code cache, GC structures and native libraries also take memory. With Native Memory Tracking and the jvm_buffer_* and jvm_memory_used{area="nonheap"} metrics you find which one is growing.
📖 Answer
First I make sure which case it is. When Java throws OutOfMemoryError, there is a stack trace in the log. With OOMKilled, the process dies from SIGKILL, there is nothing in the log, and kubectl describe pod shows Reason: OOMKilled and exit code 137.
A typical case: the limit is 1 GiB and -Xmx768m. The heap sits at 600 MB, but the container still dies. The remaining 256 MB is not enough for everything else: 200 threads × 1 MB of stack, 120 MB of metaspace, Netty direct buffers, the code cache.
How to check:
# at startup
java -XX:NativeMemoryTracking=summary -XX:MaxRAMPercentage=70 -jar app.jar
# while it is running, take a baseline and then look at the diff
jcmd 1 VM.native_memory baseline
jcmd 1 VM.native_memory summary.diff
summary.diff shows which section (Thread, Class, Internal, Other) has grown. From the metrics:
jvm_buffer_memory_used_bytes{id="direct"}: if it keeps growing, it is a direct buffer leak (unreleased NettyByteBufs, large NIO buffers);jvm_threads_live_threads: if it keeps growing, it is a thread leak, plus the stacks;jvm_memory_used_bytes{area="nonheap",id="Metaspace"}: dynamic class generation (proxies, Groovy scripts);- the gap between
container_memory_working_set_bytesand the sum of the JVM metrics: native code that NMT can't see (for example, glibc malloc arenas).
Practical measures: use -XX:MaxRAMPercentage instead of -Xmx to give the heap 60-75% of the limit, set -XX:MaxDirectMemorySize, and cap the thread pools. If there are many glibc arenas, MALLOC_ARENA_MAX=2 often brings RSS down noticeably.
Sign up to mark studied questions and save your progress.