Video in progress
A Java process's RSS grows over time, while NMT shows stable memory. What role do glibc malloc arenas play here?
glibc creates a separate malloc arena for each group of threads and doesn't always return freed memory to the OS. In a Java process with many threads, this fragmentation pushes RSS well above what NMT shows.
📖 Answer
NMT counts only the memory the JVM itself allocated. But both the JVM and JNI libraries (zlib, SSL, the native part of JDBC drivers) ultimately go through glibc malloc. To reduce lock contention, glibc creates up to 8 × cores arenas on a 64-bit system, each with 64 MB blocks.
The signs:
- many anonymous blocks of around 64 MB in
pmap -x <pid>; - RSS doesn't drop after the load;
- a difference of hundreds of MB between the NMT total and RSS.
The quick fix is to limit the number of arenas:
ENV MALLOC_ARENA_MAX=2
In many services this noticeably reduces RSS and has almost no effect on throughput. But measure this too: in an application with a lot of native allocation, contention can go up.
Another way is to attach jemalloc or tcmalloc with LD_PRELOAD. They handle fragmentation better, and jemalloc's profiling mode also helps find native leaks. In Alpine (musl) images the allocator is completely different and has its own quirks.
The worst part: this problem leads to the wrong conclusion that "Java eats a lot of memory", and teams reduce the heap. The right way is to measure memory layer by layer: heap, JVM native, malloc, and the page cache in the container.
Sign up to mark studied questions and save your progress.