Video in progress

Strong Middle ⚙️ JVM and memory

How do you analyze growth in the JVM's off-heap memory with Native Memory Tracking (NMT)?

I start the JVM with -XX:NativeMemoryTracking=summary, take a jcmd VM.native_memory baseline, and a few hours later compare it with summary.diff. The diff shows exactly which section is growing: Thread, Class, GC, Code, Internal.

📖 Answer

NMT tracks only the memory the JVM itself allocated. Its overhead in summary mode is around 5-10%, so I turn it on only on an instance where a memory problem is suspected. The flag is given only at startup, and you can't turn it on in a running process.

java -XX:NativeMemoryTracking=summary -jar app.jar

jcmd $PID VM.native_memory baseline
# ... 2-3 hours under load ...
jcmd $PID VM.native_memory summary.diff

A sample of the output:

-  Thread (reserved=412MB +180MB, committed=412MB +180MB)
          (thread #405 +178)

The answer here is clear: the number of threads grew by 178. Someone is creating a new ExecutorService on every request and not shutting it down.

Typical causes by section:

  • Class: the number of classes keeps growing: dynamic proxies, redeploys, Groovy/script generation;
  • Thread: a thread leak;
  • Code: the code cache;
  • GC: the heap grew, or remembered sets;
  • Other/NIO: direct buffers.

An important limit: NMT does not see memory that JNI libraries or glibc itself malloced. If NMT is well below the total RSS, the difference is outside it: I look at the anonymous blocks with pmap -x $PID and, if needed, attach jemalloc in profiler mode.