When a JVM in a 2 GiB container with a 1 GiB max heap gains resident memory for two days until OOM-killed while post-GC heap and all NMT categories stay flat, where is the memory going, and how do you prove it?
answer
- outside the JVM's own allocator
- outstanding versus retained
- trim and watch RSS
- malloc matched with free
basics
~20 sFlat NMT with rising RSS points outside the JVM's own allocations: a native library leaking malloc'd memory, or glibc arenas retaining freed memory. VM.info's outstanding-versus-retained line, a native heap trim and async-profiler's nativemem leak profile tell them apart.
solid answer
~50 sFirst I confirm the gap: anonymous RSS from `jcmd <pid> VM.info` keeps rising while NMT's committed total stays flat, so the growth is not the JVM's own allocations. That leaves two main suspects. A **native leak**: a JNI or other native library calling `malloc` without freeing. Or **glibc retention**: freed memory kept in malloc arenas, which multiply with threads, rather than going back to the kernel. To discriminate, I read VM.info's `C-Heap outstanding allocations: …, retained: …` line over time, since a leak grows outstanding while retention grows retained, and I run `jcmd <pid> System.trim_native_heap` once: a large RSS drop means retention. For a leak, async-profiler 4.x's `nativemem` mode plus `jfrconv --nativemem --leak` shows unfreed allocations by stack. Only then do I change one thing, such as `MALLOC_ARENA_MAX`, `-XX:TrimNativeHeapInterval` or the library, and compare the RSS curve.
code
bash · 11 lines# 1. is the growth inside or outside NMT?
jcmd <pid> VM.native_memory summary.diff scale=MB
jcmd <pid> VM.info | grep -A6 '^Process Memory:'
# 2. retention test: does RSS fall after a trim?
jcmd <pid> System.trim_native_heap
# 3. leak test: unfreed native allocations by stack (async-profiler 4.x)
asprof start -e nativemem -f /tmp/native.jfr <pid>
asprof stop <pid>
jfrconv --total --nativemem --leak /tmp/native.jfr /tmp/native-leak.htmlgo deeper
Recall that a JVM process holds memory beyond the heap and beyond what NMT counts, such as native libraries' own allocations.
Explain the difference between memory a native library still holds and memory the C library has freed but kept, and why NMT sees neither.
Drive the discrimination: confirm the gap, read outstanding against retained, run one trim as an experiment, profile unfreed mallocs, then change a single setting and compare.
Weigh standardising allocator settings or periodic trimming across services against measuring each one, since a cap that fixes retention can cost throughput elsewhere.
## The shape of the incident A service runs in a **2 GiB** container with `-Xmx1g`. Over two days its resident memory climbs steadily until the kernel kills it. Heap usage after each collection is flat, and `jcmd <pid> VM.native_memory summary.diff` against a post-warm-up baseline shows **no category growing**. The JVM's own accounting is clean, so the evidence points outside it. The job is to name what is outside and prove it before changing anything. ## Step 1: confirm the gap is real Before hunting, check that resident memory really is outgrowing what the JVM tracks: - Take `jcmd <pid> VM.info` and read its **Process Memory** section: `Resident Set Size` with its split into `anon`, `file` and `shmem`. - Compare **anonymous** RSS with NMT's committed total at the same moments. File-backed pages (the JVM's shared libraries, mapped files) are not NMT's to count. - Plot both over hours. A stable offset is overhead; a widening gap is the incident. If the gap widens while NMT is flat, two hypotheses remain, and both live in the C heap. ## Step 2: name the two candidates **Native leak.** Some native code calls `malloc` directly, not through the JVM's allocator, and never frees: a JNI library, a native dependency reached through the foreign function API, a library bundled inside a dependency. NMT never saw the allocation, so no category grows. **glibc retention.** The memory was freed, but the C library kept it. glibc hands contending threads separate **malloc arenas** to avoid lock contention, each made of large anonymous regions. Freed chunks are reused inside their arena but are often not returned to the kernel, especially when a few long-lived chunks pin a region. With many threads allocating in bursts, each arena keeps its high-water mark, and RSS creeps up although live native memory is constant. | Evidence | Native leak | glibc retention | |---|---|---| | VM.info `outstanding allocations` | grows | flat | | VM.info `retained` | flat | grows | | RSS after `System.trim_native_heap` | barely moves | drops sharply | | nativemem `--leak` flame graph | a stack with unfreed bytes | nothing significant | ## Step 3: collect the discriminating evidence 1. **Read the glibc line over time.** On glibc, VM.info prints `C-Heap outstanding allocations: …K, retained: …K`. Live allocations rising points to a leak; retained memory rising with flat outstanding points to retention. 2. **Run one trim as an experiment.** `jcmd <pid> System.trim_native_heap` (Linux only) asks the C library to give free memory back. If RSS falls by hundreds of megabytes, that memory was retained, not leaked. Run it once, as a test, and watch the curve afterwards. 3. **Profile unfreed native allocations.** async-profiler 4.x has a `nativemem` mode that records `malloc`, `realloc`, `calloc` and `free` with their addresses so allocations can be matched with frees. Record with `asprof start -e nativemem -f native.jfr <pid>`, stop it, and convert with `jfrconv --total --nativemem --leak native.jfr leak.html`. The flame graph shows only allocations without a matching free, by native and Java stack. By default the converter ignores allocations from the last 10% of the recording, so the youngest, still-in-use allocations do not swamp the result. These tests do not need a restart, which matters when the growth takes two days to reproduce. ## Step 4: change one thing and compare Only when the evidence names the cause: - **Leak**: fix or upgrade the library, or close the native resource the Java side forgets to release, then confirm the leak stack is gone from a new `--leak` profile. - **Retention**: cap arenas with the `MALLOC_ARENA_MAX` environment variable, or let the JVM trim periodically with `-XX:TrimNativeHeapInterval=<ms>` (0, the default, disables it; glibc on Linux only). Both trade some malloc performance for a lower resident set, so measure throughput as well as the RSS curve. Compare the same evidence under the same load before and after: RSS slope, retained memory, and the container's memory headroom. ## Mistakes this scenario punishes - **Raising `-Xmx`** gives the heap more room inside the same 2 GiB and leaves less for native memory, so it can bring the kill sooner. - **Reaching for NMT detail mode** cannot help: it attributes only the JVM's own allocations, which are already flat. - **Changing allocator settings first** turns a two-day reproduction into a week of guessing, because without the discriminating evidence a flatter curve proves little. - **Reading a never-shrinking RSS as proof of a leak** confuses retention with leaking; the trim experiment separates them in seconds.
- Why do many threads make glibc retention worse?To avoid lock contention, glibc gives contending threads separate malloc arenas, each a set of large anonymous regions. Memory freed inside an arena is reused by that arena but often not returned to the kernel, especially when a few live chunks pin a region. With hundreds of request threads allocating and freeing in bursts, many arenas each keep a high-water mark, and RSS creeps up although the live total is stable.
- What does capping MALLOC_ARENA_MAX trade away, and how do you know it worked?Setting the `MALLOC_ARENA_MAX` environment variable to a small number makes threads share fewer arenas, so less freed memory is stranded, at the cost of more contention on malloc-heavy native paths. You know it worked only by comparing the same evidence: the RSS curve and VM.info's retained figure should flatten under the same load, while throughput and latency stay within budget.
- When is async-profiler's nativemem mode cheap enough to run on the affected production instance?Its documentation says the overhead depends on how many native allocations the process makes and is usually small enough for production. It can be reduced with an interval, for example `nativemem=1m` for at most one sample per allocated megabyte, and `--nofree` drops free tracking when only allocation volume, not leaks, matters.
- If every NMT category is flat, the JVM cannot be the process using the memory.
- A resident set that never shrinks after frees always proves a native leak.
- Raising -Xmx gives the JVM room to absorb native memory growth.
- NMT detail mode will show the JNI library's own malloc call sites.
- Setting MALLOC_ARENA_MAX first and watching for a week is a diagnosis.