wasAsked.

How would you investigate high heap usage, garbage collection pauses, and memory leaks in a JVM service?

PhonePe · Full Stack Developer · 3-4-years · technical

Published

Year not specified · Java, Software Engineering

Community answers

Posted by wasAsked editorial collection

Investigate with measurements in this order: confirm the symptom, look at GC behaviour, then find what holds memory. 1. Confirm what is happening - Metrics: heap used after GC (the key signal for leaks), GC pause times and frequency, allocation rate, and container memory (heap is only part of JVM memory). Micrometer exposes JVM metrics for Prometheus and Grafana. - A sawtooth pattern returning to the same baseline is normal. A rising baseline after each full GC suggests a leak. Frequent long pauses suggest heap pressure or a poor GC choice. 2. Look at GC logs and JFR - Enable unified GC logging: -Xlog:gc*:file=gc.log:time,uptime,level,tags (analyse with GCeasy or GCViewer). - Java Flight Recorder (low overhead, safe in production): jcmd <pid> JFR.start duration=10m filename=rec.jfr, then inspect allocation hotspots, GC pauses, old-object samples and threads in JDK Mission Control. 3. Find the leak - Heap dump: jcmd <pid> GC.heap_dump /tmp/heap.hprof, or -XX:+HeapDumpOnOutOfMemoryError to capture one automatically. - Analyse with Eclipse MAT: dominator tree, "Leak Suspects" report, and paths to GC roots to see what keeps objects alive. - A class histogram (jcmd <pid> GC.class_histogram) taken twice shows which object types keep growing. Common causes - Unbounded caches or static maps (use Caffeine with size limits and expiry). - ThreadLocal values not removed in thread pools. - Listeners or callbacks registered and never removed. - Large Hibernate sessions (persistence context growing during batch jobs — flush and clear periodically). - Loading entire result sets or files into memory instead of streaming. - Classloader leaks after redeployments in application servers. - Off-heap growth: direct ByteBuffers (Netty), thread stacks, metaspace — check with Native Memory Tracking (-XX:NativeMemoryTracking=summary). 4. Reduce GC pauses - Size the heap correctly for the container (-XX:MaxRAMPercentage), leaving room for non-heap memory. - Choose the collector: G1 (default) for balanced workloads; generational ZGC (Java 21+) for very low pauses on large heaps; tune pause goals sparingly. - Reduce allocation rate in hot paths (avoid unnecessary object creation, boxing and large temporary collections). 5. Validate fixes - Reproduce with load tests, compare heap-after-GC trends and pause times before and after, and add alerts on heap usage after GC and GC time percentage.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics