Video in progress

-Xmx2g is set, but the process RSS is around 3 GB. Where is the rest of the memory going?

The heap is only one part of the JVM's memory. On top of it come metaspace, each thread's stack, the JIT's code cache, the GC's internal structures, direct ByteBuffers and native libraries.

📖 Answer

A rough tally for a typical Spring Boot service:

Part Approximate size
Heap (-Xmx) 2048 MB
Metaspace (class metadata) 150-300 MB
Thread stacks (300 threads × ~1 MB) 100-300 MB
Code cache (JIT code) 50-240 MB
GC structures (G1 remembered sets etc.) a few percent of the heap
Direct buffers (Netty, NIO) from 0 to hundreds of MB
malloc arenas, native libraries varies

To get exact numbers, turn on Native Memory Tracking:

java -XX:NativeMemoryTracking=summary -jar app.jar
jcmd $PID VM.native_memory summary

The result shows reserved and committed for the Java Heap, Class, Thread, Code, GC and Internal sections. RSS is close to committed.

The practical takeaway: don't set the container limit equal to Xmx. If the total NMT shows is well below RSS, the difference is often in glibc malloc arenas. The MALLOC_ARENA_MAX=2 environment variable noticeably reduces RSS in services with many threads.