Memory Management & Garbage Collection Questions
Memory as a performance resource in garbage-collected and managed runtimes (JVM, .NET, Go, V8, CPython). Covers allocation patterns and allocation pressure (boxing, value versus reference types, stack versus heap), GC algorithms and behaviour (generational, mark-and-sweep, reference counting, concurrent and compacting collectors, GC roots), pauses and tuning, heap sizing, fragmentation, object pooling and buffer reuse, data-oriented layouts and per-object overhead, on-heap versus off-heap trade-offs, and detecting and fixing memory leaks with heap dumps and profilers, including leaks from caches, closures, goroutines, asyncio tasks and native extensions. Emphasizes how memory pressure affects throughput, latency and stability, including low-latency and frame-rate-bound applications. Pointer, ownership and manual-allocation semantics, embedded memory budgets, virtual memory and paging, generic data-processing memory tricks, and GPU framework memory are covered elsewhere.
Describe a time you had to diagnose a memory leak in production. Explain your diagnostic steps (heap dumps, profilers, flame graphs), the root cause you found, the fix you deployed, and how you monitored to ensure the leak did not recur.
Sample Answer
Short answer. Tell it as one specific incident in the order situation, the actions you personally took, the root cause, the fix and its measured result, and the guard that stopped a repeat, and be honest about what you got wrong. The example below is a model you can adapt; replace every detail and number with your own, because an interviewer will probe them.
What a strong story contains
- Situation with a measurable symptom. Not "memory was high", but a number and a consequence.
- Your actions in sequence, with the tool and what each told you. "We looked at it" is weak; "I took two heap histograms ten minutes apart" is strong.
- A root cause stated precisely: which object, held by which reference, added by which change.
- The fix, plus how you proved it worked on the same metric that showed the problem.
- Prevention and a reflection: a detection gap closed, and one thing you would do differently.
Example answer (first person)
Situation. I was on call for a Java order-API service. After a Tuesday release its instances were being restarted by the orchestrator about every nine hours, and each restart dropped in-flight requests, which showed up as a burst of 5xx errors. The JVM heap was capped at 4 GB inside a 6 GB container, so the limit that was hit was the Java heap, not the kernel's container limit: the JVM threw OutOfMemoryError: Java heap space and the instance was restarted. On the dashboard, the heap after each full collection climbed from about 1.2 GB to the 4 GB ceiling over those nine hours. That is a rise of about 2.8 GB, roughly 310 MB per hour. A rising post-collection floor, as opposed to a rising raw number, is what told me this was a leak and not just a busy period.
Actions.
- Contained it. I did not start with the cause. We shortened the interval between planned rolling restarts to six hours (more frequent than the nine hours it took a leaking instance to run out), so each instance was restarted on our schedule before it reached the ceiling, which stopped the unplanned crashes and the 5xx bursts while I investigated.
- Narrowed it to one object type. On an instance I had taken out of the load balancer, I ran
jcmd <pid> GC.class_histogramtwice, ten minutes apart. One entry, a metrics class (Micrometer's timer, the object that records how long an operation took), had grown by tens of thousands of instances while everything else was flat. This histogram reports live objects by class, so growth in it is retention, not just allocation. - Found who was holding them. I took a heap dump with
jcmd <pid> GC.heap_dumpfrom that isolated instance (the jcmd docs list the impact as high and say it triggers a full collection unless-allis given, which is why I used an instance with no traffic) and opened it in Eclipse MAT, a heap-dump analyser. Its dominator tree lists objects by retained size, the memory that would be freed if that object disappeared (an object dominates another when every reference path from a GC root to the second goes through the first); it showed the metrics registry, the in-memory object that holds every meter the application has created, retaining most of the heap. "Path to GC roots" shows the chain of references that keeps one object alive, and it ended at the registry's internal map of meters. - Tied it to a code change. Reading the diff of the release, a new timer had been created with a tag built from the order ID. A tag is a label on a metric, and each distinct combination of metric name and tag values is its own meter series, which Micrometer keeps as a meter object in the registry for the life of the process. Cardinality is the number of distinct series, and an order ID has one value per order, so the cardinality grows without bound. In the dump those meters were all still registered and referenced by the registry, so every order added an entry that was never released. Micrometer's own documentation warns that tag values from user-supplied sources can blow up a metric's cardinality and should be bounded. The numbers fit: the service handled about 50 orders per second, which is 180,000 an hour and 30,000 new meters in each ten-minute histogram interval (the "tens of thousands" above), and 310 MB per hour divided by 180,000 orders is about 1.7 KB retained per order, a plausible size for a timer with its tags and registry entry. (These figures are illustrative; use your own.)
I should say that, after containing it and before the histogram in step 2, I spent a while on a flame graph (a chart of the call stacks sampled over time, where wider boxes mean more samples), and it did not help: an allocation flame graph shows where memory is allocated, which was a busy, unremarkable code path, not what stays retained. The histogram and the dominator tree were what answered the question.
Fix. I changed the tag to a bounded value (the order's status and the customer tier, a few dozen combinations at most) and moved the order ID to the log line, where it belongs. I also added a Micrometer meter filter (MeterFilter.maximumAllowableMetrics, which denies any meter after the registry reaches a set count) so a future mistake would be capped instead of fatal.
Result and monitoring. I deployed it to one canary instance first and watched the post-collection heap floor. It stayed near 1.3 GB over 72 hours of normal traffic where the old build would have crashed about eight times (72 hours / 9 hours per leak cycle) without our six-hour restarts. I then rolled it out and put the restart interval back to normal. To catch this class earlier I added an alert on the slope of the post-collection heap floor (not on the usage percentage) and a code-review checklist line: "does any new metric tag or map key have unbounded values?".
What I would do differently. The release had no soak test, so a nine-hour leak could not show in our twenty-minute pre-release load test. I proposed and later ran a four-hour soak stage on every release candidate. I would also have pulled the heap dump as soon as the rising floor appeared on the dashboard, which was hours before the first restart, instead of detouring through the flame graph.
Common mistakes when telling this story
- Claiming a result with no metric ("it got better").
- Saying "we" for every step so your own contribution is invisible.
- Naming tools without saying what each one told you.
- A neat story with no mistake in it, which reads as rehearsed.
- Skipping detection and prevention, and ending at "I fixed the bug".
If you have no production leak story
Use the closest real one (a staging or test-environment leak, a leak you found in a colleague's code review, or a memory problem in a side project) and say plainly where it ran. A smaller true story with real steps beats a large invented one.
Your JVM services have rare but severe 99.99th percentile latencies caused by long GC pauses. How would you attack it at the runtime, application and container levels, and how would you measure the improvement and roll out safely?
Sample Answer
Short answer. Start by making the 99.99th percentile (p99.99) measurable, because at that level most dashboards and load tests cannot see it. Then attribute each tail event to GC, to something else on the machine, or to the container, and attack in three layers: collector and heap settings (runtime), allocation behaviour (application), and memory and CPU limits (container). Prove each change with a before and after on the same traffic, and roll out one canary at a time. The p99.99 is the latency that 99.99% of requests beat, so one request in 10,000 is slower. A stop-the-world pause is a stretch where the collector halts every application thread, so every request in flight shares that delay.
Step 0: can you even see p99.99?
Compute the sample size. To observe about 100 requests above p99.99 you need 100 / 0.0001 = 1,000,000 requests. At 500 requests per second that is 2,000 seconds, about 33 minutes, per instance per measurement. A five-minute load test at that rate sends 150,000 requests and contains about 15 tail events, which is not enough to compare two configurations. Also:
- Use histograms that keep the tail (HdrHistogram is a library that records latencies into fine-grained buckets so any percentile can be read later; a metrics system's native histograms work too), not averages or pre-computed percentiles. Percentiles cannot be re-aggregated across instances: the p99.99 of three instances is not the average of their three p99.99 values, whereas their bucket counts can be summed and the percentile read from the sum.
- Measure latency from when the request should have started, not from when the client got round to sending it, or a stall hides itself by delaying the very requests that would have recorded it (this is called coordinated omission). Toy case: a load generator sends one request every 10 ms and waits for each reply. The server freezes for 1 second. A naive timer records one slow request of about 1,000 ms, because the generator was blocked and sent nothing else. In reality 100 requests were due during that second, and each would have waited between 0 and 1,000 ms. Timing each request from its scheduled send time records all 100 of them, and the tail then shows what users experienced.
- Keep the raw pause list from the GC log so you can match each tail event to a pause by timestamp.
Step 1: attribute the tail
Enable -Xlog:gc:file=gc.log. For every slow request (or every spike) decide which bucket it belongs to:
- A GC pause covers it. Pause duration is about equal to the extra latency. This is your GC tail.
- No pause covers it but the container was CPU-throttled. Read the container's
cpu.stat(cgroup v2): it hasnr_throttledandthrottled_useccounters, and a rising count in the spike window means the CPU limit paused the whole process, which looks identical to a GC pause from the outside. Run in apython:3.12-slimcontainer started with--cpus=0.5, with a 3-second busy loop (python -c 'import time; t = time.time(); exec("while time.time() - t < 3: pass")') followed bycat /sys/fs/cgroup/cpu.stat /sys/fs/cgroup/cpu.max, it printed:
usage_usec 1523452
...
nr_periods 31
nr_throttled 30
throttled_usec 1499386
...
(cpu.max) 50000 100000
(... marks lines of cpu.stat that were left out; the exact counts differ from run to run, so treat these figures as illustrative.)
cpu.max reads "50,000 microseconds of CPU allowed per 100,000 microsecond period", which is half a CPU. nr_periods counts the 100 ms accounting periods that have elapsed, nr_throttled counts the periods in which the process used up its quota and was frozen until the next period, and throttled_usec is the total frozen time (about 1.5 s here). The busy loop was throttled in nearly every period. In production the signal is the change in nr_throttled and throttled_usec between two reads taken around the spike: any increase that lines up with a slow request, with no GC pause covering it, points at the CPU limit. The other fields in the file are not needed for this check.
3. Neither. A slow downstream call, a lock, a synchronous disk write, a TCP retransmit (the network resending a lost packet, which adds a timeout-sized delay): trace the slow requests (record where each one spent its time with distributed tracing, which follows a request across services) rather than guessing.
Only bucket 1 is a GC problem. A common mistake is spending a month tuning the collector for a tail that belongs to bucket 2.
Step 2: runtime level
The usual order is to fix the full GCs and evacuation failures first, because they are the largest pauses, and to treat a collector change and pre-touching as the next steps.
- Eliminate full GCs and evacuation failures. (An evacuation failure is G1 running out of free space to copy surviving objects into; Oracle's G1 guide notes that full GCs are typically preceded by collections that report one.) If the log shows them on G1, they are the tail: add heap headroom, start marking earlier, or reduce allocation, per Oracle's G1 tuning guide.
- Choose the collector deliberately. G1 is the default on most configurations (Oracle's collector guide), with a pause-time goal that is a target, not a guarantee. For services that must keep worst-case pauses small, Oracle's guide points to ZGC, which targets pauses under a millisecond independent of heap size (
-XX:+UseZGC -XX:+ZGenerationalon JDK 21). The cost is more CPU and a need for headroom, so it is a trade for a tail-latency SLO, not a free upgrade. - Pre-touch the heap with
-XX:+AlwaysPreTouchso page faults for newly committed memory happen at start-up instead of under load. (A page fault is the operating system lazily handing a process a real memory page the first time it touches it; each one costs microseconds, and a collector touching fresh heap in the middle of a pause pays for many.) The java command documentation says that by default pages are committed as the application uses the heap. Cost: slower start and the memory is resident from the beginning. - Make sure pause and GC data is logged in production permanently, not only when someone is debugging.
Step 3: application level
The collector's job is proportional to what you allocate and keep alive, so this is usually the biggest lever:
- Reduce allocation rate on the hot path: reuse buffers, avoid per-request string building and boxing in tight loops, stream instead of materializing whole payloads.
- Reduce the live set: bound caches, drop references early, avoid keeping large request graphs alive across many young collections.
- Avoid very large arrays on the hot path: in G1 they are humongous objects (an object at least half a heap region in size) and are allocated in contiguous regions, which can fragment the heap.
- Pooling and off-heap only where a profile shows allocation dominates, because pools add leak and contention risks and off-heap memory is not tracked by the heap limit (
-XX:MaxDirectMemorySizebounds direct buffers).
Step 4: container level
- Heap versus container limit. The JVM's default maximum heap is 25% of available memory (
-XX:MaxRAMPercentage, default 25 per the java command documentation). Runningjava -XX:+PrintFlagsFinal -versionin a container started with--memory=1g --cpus=2shows it:MaxHeapSizewas 268,435,456 bytes (256 MiB). With-XX:MaxRAMPercentage=70it became 752,877,568 bytes (718 MiB). The rest of the limit has to cover thread stacks, metaspace, direct buffers and the JVM itself, so setting the heap to nearly 100% of the limit gets the process killed by the kernel instead of pausing. - The JVM may choose a different collector in a small container. In the same runs, the 1 GB container (2 CPUs) selected the Serial collector (
UseSerialGC = true,UseG1GC = false), while a 2 GB container with 2 CPUs selected G1. The JVM picks Serial instead of G1 when it sees fewer than two CPUs or a small memory limit, so the collector depends on the container's CPU and memory settings as well as on the JDK build (Temurin 21 here); check it on yours. A service that assumed G1 may be running Serial, with entirely different pauses, until you set-XX:+UseG1GCor-XX:+UseZGCexplicitly. - CPU limits. GC worker thread counts follow the CPUs the JVM believes it has, and a tight CPU limit can throttle the process mid-pause. Raise the limit or remove it for latency-critical services, and watch
nr_throttled.
Step 5: measure the improvement and roll out safely
- Record a baseline on a canary and a control instance at the same time, same traffic, for long enough to see at least 100 tail events (the computation above).
- Change one thing on the canary. Compare p99.99, p99.9, GC pause list, CPU usage, memory and throughput, not only the tail: a change that fixes the tail by consuming twice the CPU needs a cost conversation.
- Pre-agree a rollback trigger (for example canary p99.9 worse than control for 15 minutes, or any OOM kill) and keep the old flags in the deploy config.
- Widen in stages (one instance, one zone, half the fleet, everyone), holding at each stage for a full traffic cycle that includes your peak.
- After rollout, keep the tail histogram and GC pause dashboard, and alert on the tail, so a later release cannot undo it unnoticed.
Recommendation
Do the arithmetic and the attribution first. If GC pauses explain the tail, reduce allocation and add heap headroom, because that helps any collector, then move latency-critical services to ZGC if the pause log still shows pauses above the target, accepting its CPU cost. If throttling or a downstream explains it, no collector change will help. What would flip it: a tail event with no covering pause and a clean cpu.stat means the cause is not GC or the container, and the next tool is distributed tracing.
How do large pages and NUMA affect GC and memory performance for a JVM process? When would enabling huge pages help the collector, and when could it hurt?
Sample Answer
Short answer. Huge pages and NUMA both change where the collector's memory lives, and both can help or hurt. Huge pages (2 MiB instead of 4 KiB on x86-64 Linux) mean far fewer page-table entries (the records that map program addresses to physical memory) and TLB misses (the CPU's address-translation cache missing; both are defined under Terms) over a multi-gigabyte heap, which speeds up marking, copying and allocation, but backing the heap with them can add compaction stalls (pauses while the kernel shuffles memory to create a contiguous 2 MiB block) and wasted memory. On Linux the kernel can hand out huge pages automatically, called THP (transparent huge pages). NUMA (non-uniform memory access: on a multi-socket server each CPU socket has its own local RAM and reaches the other socket's RAM more slowly) matters when one JVM spans sockets: a NUMA-aware collector places young objects (the newly allocated ones, kept in the young generation region of the heap) on the node (one socket plus its local RAM) of the thread that allocates them. Enable huge pages for a large, latency-sensitive heap after measuring; enable NUMA support only on a host that really has several nodes and a JVM that spans them.
Terms
A page is the unit the operating system maps memory in; the page table maps virtual to physical addresses, and the TLB (translation lookaside buffer) is a small CPU cache of recent translations. A TLB miss forces a page-table walk. TLB reach is how much memory the TLB can cover at once: entries x page size. Touch more memory than that and translations start missing, so a larger page size stretches the reach. A page fault is the trap taken when a page is touched for the first time (or is not mapped); the kernel then finds and zeroes a physical page.
Why huge pages help a collector
A collector sweeps across the whole heap, so it touches many distinct pages. Illustrative arithmetic with a 32 GiB heap and a hypothetical 1,024-entry TLB (real sizes differ by CPU):
- 4 KiB pages: 2^35 / 2^12 = 8,388,608 pages to map; TLB reach = 1,024 x 4 KiB = 4 MiB.
- 2 MiB pages: 2^35 / 2^21 = 16,384 pages to map; TLB reach = 1,024 x 2 MiB = 2,048 MiB.
Fewer translations and misses means less time per object scanned and copied. The 2 MiB case covers 512 times more memory per TLB entry set (2,048 MiB versus 4 MiB), though still only 1/16 of a 32 GiB heap, so misses fall sharply rather than vanish. This benefits big-heap collectors the most, especially ones that follow references from object to object (pointer-chasing), where each hop may land on a different page.
What the JVM gives you (JDK 21 man page unless stated)
Usual order of trial: -XX:+UseTransparentHugePages with -XX:+AlwaysPreTouch first, because it needs no reserved pool; -XX:+UseLargePages only when an administrator has reserved huge pages; -XX:+UseNUMA only on a multi-node host.
-XX:+UseLargePages: explicit large pages. On Linux the pages must be reserved ahead of time, for exampleecho 4096 > /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepagesbacks 8 GB with 2 MB pages. Off by default.-XX:+UseTransparentHugePages(Linux): lets the kernel promote ranges to huge pages dynamically. Off by default; the man page warns of performance problems as the OS moves other pages around to create huge pages, and calls the option available for experimentation.-XX:+AlwaysPreTouch: the JVM touches every heap page at startup instead of on first use. It moves page-fault cost out of the request path into slower startup, and with huge pages it makes the kernel do the allocation work once, up front.-XX:+UseNUMA: NUMA-aware allocation. The JDK 21 man page text says it applies to the parallel collector, but JEP 345 (JDK 14; a JEP is a JDK Enhancement Proposal, the design document for a JDK feature) added support for G1 (a region-based collector that does most work in short pauses; the parallel collector is the throughput-oriented one that stops all application threads to collect): heap regions are spread across nodes (a NUMA node is one socket plus its local RAM) and new objects are allocated on the node of the allocating thread. The JEP limits this to the young generation (where new objects are allocated; collecting it means evacuating, that is copying, the survivors out of a region) (old-generation objects are not kept on one node) and Linux only.
When huge pages help and when they hurt
Help:
- A heap of many GiB, high allocation rate, and collection time visibly dominated by memory stalls (check with
perf statTLB-miss hardware counters, whose event names vary by CPU,perf listshows yours, or compare GC pause totals with and without the flag). - With
AlwaysPreTouch, because the heap is then mapped and zeroed at start, so no first-touch faults hit user requests.
Hurt:
- Compaction stalls with THP. Two kernel settings matter and they are easy to mix up.
/sys/kernel/mm/transparent_hugepage/enableddecides who may get huge pages:alwaysfor every process,madviseonly for regions that ask viamadvise(MADV_HUGEPAGE)(what the JVM does with-XX:+UseTransparentHugePages),neveroff./sys/kernel/mm/transparent_hugepage/defragdecides what an allocation does when no free 2 MiB block exists. The kernel documentation says that withdefragset toalwaysan application requesting THP "will stall on allocation failure and directly reclaim pages and compact memory", and thatmadvise, the default, does the same but only for regions that have usedmadvise(MADV_HUGEPAGE), so a JVM heap started with the flag takes that direct path;deferinstead wakes background kernel threads (kswapd to reclaim, kcompactd to compact) and the application uses regular pages until huge pages become available;nevermakes no compaction attempt. Compaction means the kernel copies in-use pages to gather a free contiguous 2 MiB block; direct reclaim means the requesting thread itself frees pages on the spot instead of waiting for a background kernel thread. Those stalls land in your tail latency (the slowest requests, usually measured as p99, the latency that 99% of requests beat). - Memory bloat. The kernel documentation warns that an application may map a large region and touch only one byte, and a 2 MiB page is allocated instead of 4 KiB. Mostly-empty heap regions and small containers pay for it in resident memory, which (resident memory is the RAM the process actually occupies) can push a container over its limit.
- Explicit pages need reservation. If the pool was not reserved, the JVM cannot use it. On the probe host below it printed a warning and disabled the feature.
- Slower startup from pre-touching a large heap.
Hurts for NUMA:
- A single-socket host, or a JVM pinned to one node, has nothing to optimise.
- The JEP's assumption is that short-lived objects are mostly touched by the thread that allocated them. A workload that hands objects to other threads often (queue-based pipelines) loses the locality and can regress.
- Old-generation data is not placed by node, so a large long-lived cache still sees remote accesses.
What the flags report on a test host
The probe prints the heap size; the flags are the ones above, and -Xlog:gc+init makes the JVM report the outcome.
public class HeapPageProbe {
public static void main(String[] args) {
System.out.println("max heap MB = " + Runtime.getRuntime().maxMemory() / (1024 * 1024));
}
}
In eclipse-temurin:21-jdk (a Linux container on a Mac, 14 CPUs visible, /sys/devices/system/node absent, THP mode madvise), each variant was run as java -Xmx256m -Xlog:gc+init <flag> HeapPageProbe.java and filtered (with grep) down to the Large Page, NUMA and warning lines, so the other gc,init lines are skipped; the timestamps differ from run to run:
$ java -Xmx256m -Xlog:gc+init HeapPageProbe.java [other lines skipped]
[0.005s][info][gc,init] Large Page Support: Disabled
[0.005s][info][gc,init] NUMA Support: Disabled
$ java -Xmx256m -Xlog:gc+init -XX:+UseTransparentHugePages HeapPageProbe.java
[0.003s][info][gc,init] Large Page Support: Enabled (Transparent)
[0.003s][info][gc,init] NUMA Support: Disabled
$ java -Xmx256m -Xlog:gc+init -XX:+UseLargePages HeapPageProbe.java
[0.000s][warning][pagesize] UseLargePages disabled, no large pages configured and available on the system.
[0.002s][info ][gc,init ] Large Page Support: Disabled
[0.002s][info ][gc,init ] NUMA Support: Disabled
$ java -Xmx256m -Xlog:gc+init -XX:+UseNUMA HeapPageProbe.java
[0.002s][info][gc,init] Large Page Support: Disabled
[0.002s][info][gc,init] NUMA Support: Disabled
Reading it: Large Page Support says whether the heap is backed by large pages and how (Enabled (Transparent) means the kernel's THP), NUMA Support says whether NUMA-aware placement is active, and a [warning][pagesize] line explains a request the JVM had to drop. Here THP turned on without any reservation; explicit large pages were refused because none were configured; NUMA support stayed disabled because the host exposes no NUMA topology. This probe shows the flags and their reporting, not a speedup; it ran on a virtual machine, so it is not a benchmark.
How to decide
- Check the host: THP mode in
/sys/kernel/mm/transparent_hugepage/enabled, free huge pages in/proc/meminfo, and whether the host has more than one NUMA node. - Baseline: record GC pause percentiles, total GC CPU time and resident memory with default settings.
- Change one thing at a time under production-like load:
-XX:+UseTransparentHugePageswithAlwaysPreTouch, then NUMA if the JVM spans nodes. Keep the change only if p99 latency or GC time improves and resident memory stays within the container limit. - Roll back if you see tail spikes that line up with kernel compaction or resident memory near the limit.
I would start with THP in madvise mode plus -XX:+UseTransparentHugePages and AlwaysPreTouch for a heap of several GiB on a dedicated host, and leave NUMA off unless the process spans sockets. That would flip to no huge pages for a small heap or a memory-tight container, and to explicit pre-reserved huge pages if THP compaction stalls show up. Before giving up on THP, check the defrag setting: with the default madvise the JVM's heap takes the direct reclaim and compaction path described above, and defer moves that work to background kernel threads at the cost of the heap starting on regular pages. defer+madvise does not help here: it still enters direct reclaim and compaction for regions that used madvise(MADV_HUGEPAGE), which is what the JVM heap does, and only other regions get the background path.
A long-running Java service shows heap utilisation creeping up over weeks. Walk me through finding out whether it is a true leak or just retained cache, what you would capture in production, and how you would fix and verify it.
Sample Answer
Short answer. Commit to a plan that separates the two cases by the shape of the heap after full collections, then proves the retaining path with a heap dump, then fixes and verifies with a soak test. A cache converges (rises, then plateaus at its configured limit). A leak does not (the floor keeps rising for the same load).
Step 1: classify the growth from data you already have
- Look at heap after each collection (live data), not heap used. Used heap climbs naturally because the collector runs lazily. Plot old-generation occupancy after full or mixed collections (a mixed collection is a G1 young collection that also reclaims some old-generation regions) over weeks, next to traffic.
- Leak: the post-collection floor rises monotonically, independent of load, until collections run back to back and an
OutOfMemoryErrorfollows. Retained cache: floor rises, then flattens near the cache's maximum size. - Direct test: if the service has a cache-clear or size-reduction switch, use it once. If the floor drops back and then regrows to a plateau, it is a cache. If it barely drops, something else holds the memory.
- In the GC log, watch for the pattern the HotSpot troubleshooting guide walks through: a Full GC that reclaims almost nothing (its example is
Pause Full (Ergonomics) 45M->45M(48M)), which it says means either the heap is smaller than the application needs or there is a leak.
Step 2: compare heap contents at two points in time
For most leaks, Steps 1 and 2 (the post-collection floor, then a histogram diff and a heap dump) are what find the cause; JFR, NMT and a profiler are for the cases below where those leave a gap.
The cheapest capture: jcmd <pid> GC.class_histogram (instances and bytes per class). Take two, an hour apart, and diff. Whatever class grows with time is the suspect. Caveat shown in the demo below: the histogram forces a full collection (the log shows Pause Full (Heap Inspection Initiated GC)), so take it on one instance behind a load balancer, not on every replica at once.
For the retaining path you need a heap dump: jcmd <pid> GC.heap_dump filename=/path/heap.hprof, or -XX:+HeapDumpOnOutOfMemoryError set at startup so the dump is waiting after a crash. A dump pauses the application while it is written and produces a file on the order of the heap size, so confirm disk space and run it on a drained instance. Open it in Eclipse MAT or a similar analyzer, sort by retained size (memory freed if the object disappeared), and use dominator tree (what each object exclusively keeps alive) and path to GC roots (the reference chain from a root to the suspect). The chain ends at the thing to fix: a static map, a listener list, a ThreadLocal on a pooled thread, a queue with no consumer. (A ThreadLocal gives each thread its own private value. A pooled thread lives as long as the pool does, so a large value stored in a ThreadLocal and never removed stays reachable from that thread indefinitely.)
Java Flight Recorder (JFR) is the usual lower-impact option for production; the troubleshooting guide describes recording overhead as very low. The dump step that adds root paths is not cheap, though. The guide's recipe is -XX:StartFlightRecording=... to record, jcmd <pid> JFR.dump filename=recording.jfr path-to-gc-roots=true to dump, and jfr print --events OldObjectSample file.jfr to list sampled long-lived objects with their root paths. The guide notes that path-to-gc-roots=true creates overhead similar to a full garbage collection, so take that dump on one instance, as with a heap dump. Because it is sampled, measure its overhead on a canary before leaving it on fleet-wide. A sampling profiler can attribute allocations to call sites: async-profiler (an agent that runs inside the target JVM) does this with its --alloc option, for example asprof -e cpu --alloc 2m -d 30 -f profile.jfr <pid>, which takes one allocation sample per 2 MB allocated on average and writes a recording you can open in a JFR viewer.
Step 3: rule out memory the heap does not hold
If container memory (RSS, the resident set size the OS sees) grows while heap after collection is flat, the leak is off-heap: direct ByteBuffers (buffers whose bytes live in native memory outside the heap), thread stacks, metaspace (the native memory holding loaded class definitions), native libraries. Start the JVM with Native Memory Tracking (NMT, the JVM's own accounting of its native allocations) switched on, -XX:NativeMemoryTracking=summary, then jcmd <pid> VM.native_memory baseline and later VM.native_memory summary.diff to see which category grew. Check the BufferPoolMXBean "direct" pool for direct-buffer counts. Heap size plus those categories should account for RSS; the gap is native code.
Step 4: what to turn on in staging and production
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=<volume with space>, GC logging (-Xlog:gc*:file=gc.log, rotated), NMT summary mode, JFR available on demand, and the JVM's memory metrics exported to your metrics system (for example through Micrometer to Prometheus), with alerts on the post-collection floor rather than on raw heap used (which is noisy by design).
A leak reproduced and found
import java.util.*;
public class GrowingMapLeak {
// A static field is a GC root: everything reachable from it stays alive.
static final Map<Long, byte[]> sessionPayloads = new HashMap<>();
public static void main(String[] args) throws Exception {
for (long id = 0; id < 400_000; id++) {
sessionPayloads.put(id, new byte[8 * 1024]); // never removed
if (id % 100 == 0) Thread.sleep(20);
}
System.out.println("done: " + sessionPayloads.size());
}
}
Run: javac -d /tmp/o GrowingMapLeak.java, then java -cp /tmp/o -Xmx256m -Xlog:gc -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp/o/leak.hprof GrowingMapLeak (OpenJDK 21.0.12 in a container), plus two jcmd <pid> GC.class_histogram calls about one second apart, give these excerpts (G1 is the default collector on a machine with at least 2 CPUs and roughly 1.8 GB of memory; in a one-CPU or smaller container the JVM picks Serial, and the late full collections then print as Pause Full (Allocation Failure) instead of G1 Compaction Pause, while the histogram-triggered line is the same):
1: 21413 110345968 [B (java.base@21.0.12.1) <- first histogram
1: 26313 150565168 [B (java.base@21.0.12.1) <- one second later
[3.236s][info][gc] GC(4) Pause Full (Heap Inspection Initiated GC) 109M->107M(254M) 9.178ms
[7.358s][info][gc] GC(15) Pause Full (G1 Compaction Pause) 255M->246M(256M) 5.198ms
java.lang.OutOfMemoryError: Java heap space
Dumping heap to /tmp/o/leak.hprof ...
[B is byte[]: instance count and bytes both grow between snapshots and the full collections reclaim almost nothing (255M to 246M). The dump's path to GC roots would end at the static sessionPayloads field of GrowingMapLeak, which is a root.
Step 5: fix and verify
Fix by cause: bound the cache (maximum entries or bytes plus expiry, so it has a ceiling), remove listeners or registrations on close, clear ThreadLocals in pooled threads, close consumers and queues. Verify: deploy the fix to one instance, replay or mirror production load for several multiples of the time it took the leak to show (hours, not minutes), and confirm the post-collection floor goes flat while the class histogram no longer shows the suspect growing. Keep the dump-on-OOM flag on so a regression leaves evidence.
If the result is a cache that is merely too large for the pod, the fix is a smaller limit or a bigger heap, and the verification is the plateau sitting comfortably below the heap limit. Remember that jcmd, jmap, JFR and NMT are JDK tools; on other runtimes the same sequence applies with that runtime's heap snapshot tool.
A JVM service uses large direct ByteBuffers. Its heap looks healthy, but the container is OOM-killed. How do you find where the memory went, and what would you change about how the buffers are allocated and released?
Sample Answer
Why the heap looks healthy while the container dies. A direct ByteBuffer (from ByteBuffer.allocateDirect) keeps its bytes in native memory outside the garbage-collected heap, so only a tiny wrapper object is on the heap. A container's memory limit (a Linux cgroup, a kernel feature that caps a group of processes) counts the whole process: heap + direct buffers + thread stacks + Metaspace (class metadata) + JIT code + GC bookkeeping. When the total passes the limit the kernel's OOM killer sends SIGKILL (a signal that terminates a process immediately and cannot be caught or handled), with no Java exception and no heap dump. Heap graphs and -Xmx never see it.
Evidence from a run (JDK 21 container, -Xmx512m -XX:NativeMemoryTracking=summary). The program allocates eight 32 MiB direct buffers and prints heap, the direct buffer pool and the process's resident memory (RSS, the physical memory the process occupies), then drops the references, calls System.gc(), and finally keeps allocating until the cap is hit:
import java.lang.management.BufferPoolMXBean;
import java.lang.management.ManagementFactory;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public class DirectDemo {
static long rssMiB() throws Exception {
for (String line : Files.readAllLines(Path.of("/proc/self/status"))) // reading a file through NIO
if (line.startsWith("VmRSS:")) return Long.parseLong(line.replaceAll("\\D+", "")) / 1024;
return -1;
}
static void report(String label) throws Exception {
BufferPoolMXBean direct = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class).stream()
.filter(p -> p.getName().equals("direct")).findFirst().get();
Runtime rt = Runtime.getRuntime();
System.out.printf("%-28s heapUsed=%4d MiB maxHeap=%4d MiB direct(count=%d, used=%4d MiB) RSS=%4d MiB%n",
label, (rt.totalMemory() - rt.freeMemory()) >> 20, rt.maxMemory() >> 20,
direct.getCount(), direct.getMemoryUsed() >> 20, rssMiB());
}
public static void main(String[] args) throws Exception {
report("start");
List<ByteBuffer> bufs = new ArrayList<>();
for (int i = 0; i < 8; i++) bufs.add(ByteBuffer.allocateDirect(32 << 20)); // 8 x 32 MiB, native memory
report("after 8 x 32 MiB direct");
new ProcessBuilder("jcmd", String.valueOf(ProcessHandle.current().pid()), "VM.native_memory", "summary", "scale=MB")
.inheritIO().start().waitFor();
bufs = null; // drop every reference
report("references dropped");
System.gc(); // lets the Cleaner free the bytes
Thread.sleep(500);
report("after System.gc()");
List<ByteBuffer> hold = new ArrayList<>();
try {
while (true) hold.add(ByteBuffer.allocateDirect(32 << 20)); // keep going until the cap
} catch (OutOfMemoryError e) {
System.out.println("OOM: " + e);
}
}
}
It printed (the Native Memory Tracking report is abridged to its total and its Other entry, with ... where lines are skipped):
start heapUsed= 2 MiB maxHeap= 512 MiB direct(count=0, used= 0 MiB) RSS= 72 MiB
after 8 x 32 MiB direct heapUsed= 3 MiB maxHeap= 512 MiB direct(count=9, used= 256 MiB) RSS= 330 MiB
Total: reserved=2219MB, committed=597MB
...
- Other (reserved=256MB, committed=256MB)
(malloc=256MB #10) (at peak)
...
references dropped heapUsed= 4 MiB maxHeap= 512 MiB direct(count=9, used= 256 MiB) RSS= 335 MiB
after System.gc() heapUsed= 1 MiB maxHeap= 512 MiB direct(count=1, used= 0 MiB) RSS= 88 MiB
OOM: java.lang.OutOfMemoryError: Cannot reserve 33554432 bytes of direct buffer memory (allocated: 503324672, limit: 536870912)
Two counts need explaining. Eight buffers were allocated, yet count=9: reading /proc/self/status through Files.readAllLines makes the JDK's NIO layer allocate one small temporary direct buffer (8 KiB) and cache it for the thread, so it is the ninth. That cached buffer is also why count=1 and used=0 MiB remain after System.gc() (8 KiB rounds to 0 MiB): the eight 32 MiB buffers are gone and only the cached one is left. A variant that reads the file with a plain BufferedReader printed count=8 and then count=0. The last line comes from the final loop: it holds 15 buffers of 33,554,432 bytes (15 x 33,554,432 = 503,316,480) plus the 8,192-byte cached buffer, which is the allocated: 503,324,672; a 16th buffer would bring the total to 536,879,104, over the limit of 536,870,912 (512 MiB), so it throws.
What it shows: (1) 256 MiB of buffers moved RSS from 72 to 330 MiB while heap stayed at 3 MiB, which is the "healthy heap" illusion. (2) Dropping the references freed nothing (direct used still 256 MiB): the native memory is released only after a garbage collection finds the unreachable wrapper object and runs its cleanup. A service whose heap rarely collects can hold gigabytes of dead buffers. (3) After System.gc() it fell to 0 and RSS returned to 88 MiB. (4) The failed allocation message shows the cap: with no flag set, the limit in this run was 536,870,912 bytes, exactly the 512 MiB -Xmx. The JVM docs only say that if -XX:MaxDirectMemorySize is unset "the JVM chooses the size automatically"; in this run it equalled the maximum heap, so confirm it on your JVM version. The consequence is that a service can legally use heap + direct up to about twice the heap, before adding stacks and Metaspace, and a container limit sized as "heap + a bit" is too small. Note the NMT entry labelled Other held the direct memory (committed=256MB, allocated with malloc); the Total includes it.
Finding where the memory went, in order.
- Confirm it is a kernel kill and not a Java OOM.
dmesg/ the orchestrator shows exit code 137 (a process killed by a signal exits with 128 plus the signal number, and SIGKILL is signal 9) and "OOMKilled". A JavaOutOfMemoryError: ... direct buffer memorywould be a normal exception with a stack trace instead. - Compare the pieces: container RSS (cgroup memory usage) vs
Runtimeheap used vs theBufferPoolMXBeanvalues for "direct" and "mapped" (exposed by JMX, so you can chart them). If RSS is far above heap + direct pool, the memory is elsewhere. - Turn on Native Memory Tracking (
-XX:NativeMemoryTracking=summary, ordetailfor call sites; Oracle documents about 5 to 10% overhead). Thenjcmd <pid> VM.native_memory baseline, wait for growth, andjcmd <pid> VM.native_memory summary.diff scale=MB. The diff names the growing category: Java Heap, Class (Metaspace), Thread, Code, GC, Other (direct buffers appeared in Other above). - If NMT's total stays flat but RSS grows, the leak is in code NMT does not track (non-JVM code such as JNI and third-party native libraries, per Oracle's note that NMT does not track allocations made outside the JVM): use
pmap -x <pid>(a Linux tool that lists the process's memory mappings with their sizes) to find large mappings, and a native profiler (for example heap profiling in jemalloc, an alternativemallocimplementation that can record which call sites allocate; orasync-profiler, a low-overhead sampling profiler with an allocation mode) to find the callers. - If the growth is the direct pool, take a heap dump and count
java.nio.DirectByteBufferinstances and who holds them. A large number of small-looking wrappers with big capacities is the pattern.
What to change.
- Reuse instead of allocating. Allocate a few large direct buffers once (or use a pool such as Netty's pooled allocator, the buffer pool of the Netty networking library) and recycle them. Allocating a direct buffer is slow partly because the bytes are zeroed (the JavaDoc guarantees each element is initialised to zero), so churning them is costly; and because the memory is released only after a garbage collection, churn also lets dead buffers pile up.
- Release deterministically where you can.
ByteBufferhas no public close method, so memory goes only when the wrapper is collected. For new code, on Java 22 and later the Foreign Function & Memory API givesArena.ofConfined(): memory is deallocated the moment the try-with-resources block closes (JEP 454). On older versions, if you adopt a library with reference-counted buffers (Netty), release them in afinally. A leaked reference-counted buffer is a leak the GC cannot fix. - Cap it so the failure is a Java exception, not a SIGKILL. Set
-XX:MaxDirectMemorySizeexplicitly and set the container limit above heap + direct cap + Metaspace + thread stacks + headroom (a budget you compute, not a fixed ratio). A JVMOutOfMemoryErrorwith a stack trace is debuggable; an OOM kill is not. - Make collections happen. If direct buffers pile up because the heap rarely collects, a smaller young generation or a periodic cleanup is a workaround, not a fix. Check whether your service sets
-XX:+DisableExplicitGC: it turns explicitSystem.gc()calls into no-ops, which removes one way of forcing the cleanup shown above. With that flag added to the demo's command line,direct usedstayed at 256 MiB afterSystem.gc()and the final loop hit the cap with the dead buffers still in place.
What would change my choice: if buffers are few and long-lived, none of this matters beyond setting the cap. If the service handles many short requests that each take a buffer, a pool is the fix, and the direct cap is the safety net.
Unlock Full Question Bank
Get access to all 8 Memory Management & Garbage Collection interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.