Quick revision
The short answer
The container limit covers the whole process, and the heap is only part of it. We check metaspace, thread stacks, the code cache, GC structures, direct and mapped buffers and native libraries, using Native Memory Tracking (-XX:NativeMemoryTracking=summary and jcmd <pid> VM.native_memory summary) for what the JVM allocates, BufferPoolMXBean metrics for direct buffers, and OS tools or allocator profiling for memory allocated by native libraries, which NMT does not see. The lasting fix is to leave headroom: size -Xmx or MaxRAMPercentage so heap plus non-heap fits under the limit.
What to remember
In this answer, we saw that the kernel kills a container when the whole process exceeds its limit, so a healthy heap tells us little. Metaspace, thread stacks, the code cache, GC structures, direct and mapped buffers and native libraries all use memory outside the heap. Native Memory Tracking with jcmd VM.native_memory summary, baseline and diff shows which JVM area is large or growing, BufferPoolMXBean metrics show direct buffers, and OS tools or allocation profiling find native library memory that NMT cannot see. The lasting fix is sizing the heap with headroom so heap plus non-heap fits the limit.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The container limit covers the whole process, and the heap is only part of it. We check metaspace, thread stacks, the code cache, GC structures, direct and mapped buffers and native libraries, using Native Memory Tracking (-XX:NativeMemoryTracking=summary and jcmd <pid> VM.native_memory summary) for what the JVM allocates, BufferPoolMXBean metrics for direct buffers, and OS tools or allocator profiling for memory allocated by native libraries, which NMT does not see. The lasting fix is to leave headroom: size -Xmx or MaxRAMPercentage so heap plus non-heap fits under the limit.
Why this question is asked
This is one of the most confusing production problems in Java services. Pods restart with exit code 137, there is no OutOfMemoryError in the logs, and the GC logs show a heap that never goes above 60 percent. Interviewers ask about it because the answer shows whether we know that a JVM is much more than its heap, and whether we know the tools to prove where the memory went. In this answer, we will recap what kills the container, list the memory areas outside the heap, use Native Memory Tracking step by step, check direct buffers, track down native allocations that NMT cannot see, and finish with how to size the JVM so it fits.
1Who Kills the Container, and Why the Heap Looks Fine
A container's memory limit is enforced by the Linux kernel through cgroups. The kernel counts the resident memory of every process in the container, meaning the pages that are actually in RAM. When the total goes over the limit, the kernel's OOM killer sends SIGKILL, and the container exits with code 137 (128 plus signal 9). The JVM gets no chance to throw OutOfMemoryError or write a heap dump.
The GC logs only describe the heap. If -Xmx is 6 GB in an 8 GB container and the heap uses at most 3.6 GB, the remaining 4.4 GB of the limit is shared by everything else the process allocates. If that everything else grows past 4.4 GB, or the heap grows while it is large, the process is killed. So the question is always: what else is in the process?
2The Memory Areas Outside the Heap
Metaspace holds class metadata; it grows with the number of loaded classes and leaks when class loaders are not released, for example after repeated redeployments or heavy use of generated proxies. Thread stacks reserve about 1 MB per platform thread by default on 64-bit Linux (-Xss), so a service with 800 threads can commit hundreds of megabytes. The code cache holds JIT-compiled code, up to 240 MB by default with tiered compilation. GC structures such as G1's remembered sets and card tables grow with the heap size.
Then come areas the application chooses. Direct ByteBuffers, used heavily by Netty, gRPC and many HTTP clients, are capped by -XX:MaxDirectMemorySize. Memory-mapped files count while their pages are resident. Finally, native libraries loaded into the process, such as a compression library, a TLS implementation like BoringSSL, or a database driver with native parts, allocate memory with malloc that the JVM knows nothing about.
| Area | Example size | Grows with |
|---|---|---|
| Java heap (committed) | 6.0 GB | -Xmx, even when GC logs show 60 percent used |
| Metaspace | 320 MB | classes loaded, class loader leaks |
| Thread stacks | 650 MB | number of platform threads x -Xss |
| Code cache | 180 MB | JIT-compiled code, up to 240 MB by default |
| GC structures | 300 MB | heap size and collector |
| Direct buffers | 700 MB | Netty and HTTP client pools |
| Native libraries (not in NMT) | 250 MB | malloc in zlib, TLS, drivers |
3Turn On Native Memory Tracking
Native Memory Tracking, NMT, is built into HotSpot. It records every allocation the JVM itself makes, grouped by category. It must be enabled at startup, and it costs a little CPU and memory, so we turn it on in one instance or a staging copy rather than everywhere.
The first summary tells us which area is large; the diff tells us which area is growing, which is what we really want for a slow climb to the kill. In this example, the thread category grew by 388 MB in an hour, which points to a thread leak, perhaps an executor created per request and never shut down. A jstack or jcmd <pid> Thread.print would then show hundreds of threads with the same name pattern. Notice also the committed column: committed memory is what the OS has really given us, while reserved is only address space.
4Check the Direct Buffer Pools
Direct buffers appear in NMT under Other, but a direct metric is easier to watch over time. The JDK publishes BufferPoolMXBean beans named direct and mapped, and Spring Boot with Micrometer exposes them as jvm.buffer.memory.used.
If direct memory climbs steadily, the usual suspects are buffer pools that keep growing, such as Netty's pooled allocator with many arenas, or buffers that are freed only when the GC collects their small heap objects. Setting -XX:MaxDirectMemorySize to an explicit value turns a silent container kill into a clear OutOfMemoryError: Direct buffer memory, which is far easier to debug.
5Find Native Allocations That NMT Cannot See
NMT only knows about the JVM's own allocations. When C code inside a library calls malloc, NMT does not record it. So we compare: if the process's resident size from the OS is much larger than NMT's committed total, the difference is native library memory or allocator overhead.
- Confirm the killexit code 137, kernel OOM message, no Java OOM error
- Compare RSS with the committed heapthe gap is non-heap memory
- NMT summary, then baseline and diffwhich JVM area is large or growing
- Does NMT's total explain the RSS?YesFix the growing JVM areaNoNative library memory: pmap, jemalloc, profiler
- Check direct buffer metrics over timeset
MaxDirectMemorySizeto fail clearly - Resize heap and limits with headroom
6 steps in order. Play them, or step through them one at a time.
A common pattern on glibc is many 64 MB anonymous regions, which are malloc arenas created for different threads; setting MALLOC_ARENA_MAX=2 often reduces that fragmentation. For a real leak in a library, such as Inflater objects that are never ended in a compression path, we need allocation profiling: running with jemalloc and its profiling enabled, or using a profiler that can sample native allocations, such as async-profiler's native memory mode (check your version). These show the Java stack that led to each malloc.
6Leave Headroom When Sizing
Even with no leak, the budget must add up. A safe starting point is to give the heap 50 to 70 percent of the container limit with -XX:MaxRAMPercentage, set MaxDirectMemorySize explicitly when the service uses direct buffers, cap thread counts in pools, and keep an allowance of several hundred megabytes for metaspace, code cache and native libraries. For the 8 GB container in our example, -XX:MaxRAMPercentage=60 gives a heap of about 4.8 GB, which the GC logs say is plenty, and leaves about 3 GB for everything else.
7Follow-up questions
Does NMT have a performance cost?
Yes, a modest one. Summary mode adds a small amount of memory per allocation and a few percent of CPU in allocation-heavy code; detail mode, which records call sites, costs more. That is why we enable it on one instance or in a load test rather than across the fleet.
Why does the committed heap count fully even when GC logs say 60 percent is used?
Because the GC keeps heap regions committed once it has touched them, and the kernel counts resident pages, not used objects. Setting -Xms equal to -Xmx makes this explicit from the start; collectors can return unused memory to the OS, but we should not rely on that for the memory budget.
Would virtual threads help with the thread stack cost?
Often, yes. Virtual threads keep their stacks on the heap in small chunks rather than reserving a large native stack each, so a service that blocks on I/O with thousands of platform threads can cut that area sharply by moving to virtual threads.
8Conclusion
In this answer, we saw that the kernel kills a container when the whole process exceeds its limit, so a healthy heap tells us little. Metaspace, thread stacks, the code cache, GC structures, direct and mapped buffers and native libraries all use memory outside the heap. Native Memory Tracking with jcmd VM.native_memory summary, baseline and diff shows which JVM area is large or growing, BufferPoolMXBean metrics show direct buffers, and OS tools or allocation profiling find native library memory that NMT cannot see. The lasting fix is sizing the heap with headroom so heap plus non-heap fits the limit.
Open with
Exit code 137 with a heap at 60 percent tells me the kernel killed the process because its total resident memory went over the cgroup limit, so I look at everything outside the heap.
Then, if they want more
That means metaspace, thread stacks at about 1 MB per platform thread, the code cache, GC data structures, direct and mapped buffers, and memory malloc'd by native libraries. I also remember the committed heap counts in full, not just the used part. First I compare the process RSS with the committed heap to size the gap.
Then I enable Native Memory Tracking with -XX:NativeMemoryTracking=summary on one instance and run jcmd pid VM.native_memory summary, take a baseline, and run summary.diff after an hour under load to see which category grows. For direct buffers I watch the BufferPoolMXBean or jvm.buffer.memory.used, and set MaxDirectMemorySize so a leak becomes a clear OutOfMemoryError instead of a kill.
If NMT's total does not explain the RSS, the rest is native library or allocator memory, so I use pmap, try MALLOC_ARENA_MAX, or profile allocations with jemalloc or async-profiler. Finally I set MaxRAMPercentage to around 60 so heap plus non-heap fits with headroom.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A container keeps getting OOM-killed while the Java heap, as shown by GC logs, never...": https://scrivio-interview-library.netlify.app/java/foreign-memory-and-native/c982f0329b/