SteelReed

Search

Search posts, questions…

3. Advanced Java

Garbage collection in the JVM: G1, ZGC, reading GC logs and diagnosing OutOfMemoryError

Why a Java app freezes for hundreds of milliseconds or dies with OutOfMemoryError while the heap looks free; how the GC decides what is garbage, choosing Serial, Parallel, G1, ZGC or Shenandoah on JDK 25 with measurements, reading GC logs, the six kinds of OOM, finding memory leaks in production and reviewing AI-proposed JVM flags.

19 Nov 20268 min readSenior

–

1. The problem

An ordering API has a p99 of 120 ms that jumps to 900 ms every 40 minutes. Heap after GC grows from 600 MB to 1.7 GB over 6 hours, then the pod dies with OutOfMemoryError: Java heap space. Raising -Xmx from 2g to 4g: the pod still dies, after 14 hours.

2. Key idea

The JVM doesn't count references: it walks from the GC roots (local variables, static fields, live threads), marks everything reachable, and the rest is garbage. The tracing and copying done while the app is stopped (stop-the-world) is the latency spike, and it scales with live data, not with the amount of garbage.

A Java leak means still holding a reference: a static Map used as an unbounded cache, listeners never removed, a ThreadLocal never remove()d on a pool thread. The sign: heap after GC keeps growing under steady load.

Collector Use when Don't use when
Parallel batch, ETL: maximum throughput users are waiting
G1 (default) most web services, heaps from a few GB to tens of GB pauses of tens of ms already show in p99
ZGC pauses show in p99, large heaps, 10–20% spare CPU few cores, CPU already busy

Measured on JDK 25 (120 MB live data, 512 MB heap): longest G1 pause 33 ms, ZGC 0.006 ms.

2.1 Which area does an OOM name?

Read the text after the colon first.

  • Java heap space: a leak, or loading too much at once (unpaginated queries).
  • Metaspace: unbounded dynamic class generation, a ClassLoader leak on redeploy.
  • Cannot reserve N bytes of direct buffer memory: Netty or NIO holding direct buffers.
  • OOMKilled (exit code 137) is different: the kernel kills the process because total RSS exceeds the limit; no stack trace, no heap dump.

3. In Java

Few flags, a heap dump on death, a GC log to read later.

BASH
java -XX:MaxRAMPercentage=75 \
     -XX:+UseG1GC -XX:MaxGCPauseMillis=200 \
     -Xlog:gc*:file=/var/log/app/gc.log:time,uptime:filecount=5,filesize=20m \
     -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dumps \
     -XX:+ExitOnOutOfMemoryError \
     -jar app.jar
 
# One G1 log line: pause type, heap before->after(committed), pause time
# [0.087s][info][gc] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 219M->147M(512M) 30.663ms

MaxRAMPercentage leaves ~25% for off-heap memory. Other languages: Go tunes with GOGC and GOMEMLIMIT and inspects heaps with pprof; Node.js has --max-old-space-size and heap snapshots.

Finding a leak with a heap dump
  1. Confirm: heap after GC grows over hours under steady load. High usage that returns to the same level after GC is not a leak.
  2. Quick look: jcmd <pid> GC.class_histogram | head -20 twice, a few minutes apart; classes whose instance count grows are suspects.
  3. Heap dump: jcmd <pid> GC.heap_dump /dumps/app.hprof from an instance taken out of the load balancer (it pauses the app for seconds to tens of seconds).
  4. Analyse: MAT → Dominator Tree. Retained size is what would be freed if that object went away. Pick the biggest → Path to GC Roots to see what holds it, e.g. static CACHE → HashMap → 2 million entries.
  5. Fix and prove: bounded caches (Caffeine maximumSize, TTL), remove listeners; run a soak test for hours and check old-after-GC stays flat.

Heap dumps contain real data (tokens, customer details): encrypt them and delete them when done.

4. Working with AI

AI often suggests JVM flags copied from old blogs: check each against the JDK version and the pod limit.

Hand to AI: summarising GC logs, diffing two GC.class_histogram runs, soak tests.

Check in AI-written code:

  • No removed or redundant flags: UseConcMarkSweepGC, PermSize, PrintGCDetails, ZGenerational.
  • Heap plus off-heap stays below the pod limit; use MaxRAMPercentage.
  • HeapDumpPath points at a writable volume, alongside ExitOnOutOfMemoryError.
  • A collector change comes with before/after numbers (p99, CPU, throughput).

5. Exercises

Exercise 1: Review a JVM config

Pod limit 2 GiB, JDK 25. The AI wrote the flags below, saying "tuned for a 2 GiB container, low pauses, heap dumps on". Find the bugs and fix them.

BASH
java -Xms2g -Xmx2g -XX:+UseG1GC -Xmn512m -XX:MaxGCPauseMillis=50 \
     -XX:+ZGenerational -XX:+PrintGCDetails \
     -XX:+HeapDumpOnOutOfMemoryError -jar app.jar
Solution to Exercise 1
  • -Xmx2g equals the limit: heap plus metaspace, thread stacks and direct buffers exceed 2 GiB and the pod is OOMKilled with no heap dump. Use -XX:MaxRAMPercentage=75.
  • -Xmn512m stops G1 from resizing the young generation, so MaxGCPauseMillis=50 can't be met; drop -Xmn.
  • -XX:+ZGenerational is pointless (this is G1, and the flag is obsolete since JDK 24); -XX:+PrintGCDetails is gone, use -Xlog:gc*.
  • Missing a HeapDumpPath on a writable volume (the dump is lost when the pod restarts) and -XX:+ExitOnOutOfMemoryError.
  • Proof: load test with a 2 GiB limit, compare RSS (kubectl top pod) to the limit and p99 pauses before/after.

Exercise 2: Read an incident

After deploying an "in-memory exchange rate cache", old-after-GC grows from 500 MB to 1.6 GB in 5 hours under steady load. The G1 log shows Pause Full every 3 minutes; java.util.HashMap$Node in the histogram grows from 1.2 to 1.9 million in 10 minutes. Diagnose it, say what you do in the first 15 minutes, and fix the root cause.

Solution to Exercise 2
  • Diagnosis: a memory leak (heap after GC grows steadily under steady load); the suspect is the new cache's unbounded map.
  • 15 minutes: take a heap dump from an instance pulled out of the load balancer, then roll back to save traffic. Don't raise -Xmx: it only delays the crash.
  • Root fix: MAT → Dominator Tree → Path to GC Roots confirms a static map holds the entries. Replace it with Caffeine using maximumSize and a TTL, soak test for hours, and alert when old-after-GC exceeds 70% of the heap.

Summary

  • Garbage has no path from a GC root; a leak is a reference you no longer need but still hold.
  • G1 by default; ZGC when pauses show in p99 and CPU is spare.
  • Heap after GC growing over hours means a leak.
  • Read the text after the OOM colon; OOMKilled is the kernel, not the JVM.
  • Find leaks with heap dumps, not by raising -Xmx.

Read more: JVM memory areas and ClassLoaders.

Practice interview questions on this topic

All JVM questions →

Loading comments…
Next on the roadmapVirtual memory, page cache, swap and the JVM in containers