Skip to lesson

Diagnosing memory problems practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Diagnosis is mostly pattern recognition: a few shapes of output appear again and again, and each one points to one next step. This practice set trains exactly that, on real output from JDK 21.

Match tool output to the right problem

Most memory problems leave one of a handful of fingerprints. Learn them as pairs of "what you see" and "what it means".

Example 1 · Fingerprint: back-to-back full GCs

Terminal
java -Xmx64m -XX:+UseParallelGC OtpCachejstat -gccause <pid> 1000 2
Sample output
  S0     S1     E      O      M     CCS    YGC     YGCT     FGC    FGCT     CGC    CGCT       GCT    LGCC                 GCC
  0.00  19.08 100.00  91.51  50.22   4.20      3     0.105   203    19.881     -         -    19.986 Allocation Failure   Ergonomics
  0.00  19.08 100.00  91.54  50.22   4.20      3     0.105   213    20.838     -         -    20.943 Allocation Failure   Ergonomics

What this code does

  • An earlier version of OtpCache from the OutOfMemoryError lesson (2 million entries) with a 64 MB heap and the Parallel collector, about 20 seconds in. Eden is 100% full, the old generation 91.5%, and 10 full GCs ran in one second taking about 0.96 seconds of it.
  • -gccause adds the cause of the last GC (LGCC) and of the current one (GCC). Fingerprint: the heap is full of live objects and GC frees nothing. Another run of the same command ended with OutOfMemoryError: GC overhead limit exceeded. Next step: a heap dump.
  • Heap after GC (GC log) or OU (jstat) rising after every collection → objects are kept: a leak, or live data that keeps growing.
  • FGC climbing every few seconds, old generation above 90%, FGCT growing as fast as the clock → the heap is full of live objects; an OutOfMemoryError is close.
  • Heap after GC flat, but young GCs very frequent → allocation pressure: lots of short-lived garbage, not a leak.
  • Hundreds of pool-N-thread-M threads WAITING (parking) → a thread leak; "Found one Java-level deadlock" → a deadlock.
  • java.lang.Class count rising between histograms → classes loaded again and again; metaspace will grow.

When the output matches none of these and memory looks healthy, the problem is probably elsewhere: the database, the network, locks or CPU.

Read class histograms and GC logs

In a class histogram, skip the usual top rows (byte[], String, Object[]) and find your own classes. Then divide: if 100000 Registration objects come with about 300000 String and 100000 ArrayList objects, each registration brings three strings and a list.

Example 2 · A fest registration service to read

FestRegistrations.javaJava
import java.util.ArrayList;import java.util.List;
class Registration {    final String name;    final String event;    final List<String> notifications = new ArrayList<>();
    Registration(String name, String event) {        this.name = name;        this.event = event;    }}
public class FestRegistrations {    // Bug: every registration, and every SMS text sent for it, is kept forever    static final List<Registration> ALL = new ArrayList<>();
    public static void main(String[] args) throws InterruptedException {        String[] events = {"Coding Relay", "Dance Battle", "Quiz Night", "Robo Race"};        for (int i = 1; i <= 100_000; i++) {            Registration r = new Registration("Student" + i, events[i % 4]);            r.notifications.add("Registered for " + r.event + ", id " + i);            r.notifications.add("Reminder: " + r.event + " starts at 10 am");            ALL.add(r);        }        System.out.println("Registrations kept: " + ALL.size() + ". Running for 60 seconds.");        Thread.sleep(60_000);    }}
Sample output
Registrations kept: 100000. Running for 60 seconds.

What this code does

  • A college-fest app keeps every Registration, and each one keeps a list of the SMS texts sent for it. With no flags it holds about 33 MB and then sleeps for 60 seconds so you can run jcmd against it.
  • The output is labelled "Sample output" only because the program runs longer than the course checker allows; the line itself is always the same.

Example 3 · Its class histogram

Terminal
jcmd <pid> GC.class_histogram
Sample output
1040:
 num     #instances         #bytes  class name (module)
-------------------------------------------------------
   1:        302733       14510088  [B (java.base@21.0.7)
   2:        302651        7263624  java.lang.String (java.base@21.0.7)
   3:        101170        6099616  [Ljava.lang.Object; (java.base@21.0.7)
   4:        100027        2400648  java.util.ArrayList (java.base@21.0.7)
   5:        100000        2400000  Registration
   6:           733          91480  java.lang.Class (java.base@21.0.7)
   7:          1246          39872  java.util.concurrent.ConcurrentHashMap$Node (java.base@21.0.7)
...
Total        915149       33113528

What this code does

  • JDK 21, 4 seconds after start. Registration has exactly 100000 objects, and String, byte[], ArrayList and Object[] all sit at about 1 or 3 times that number: each registration brings its name and two SMS texts (3 strings, each with a byte[]) and one ArrayList with its array.
  • The event names are shared string literals, so they do not add to the count. Together, about 326 bytes stay alive per registration: small alone, but a fest with lakhs of registrations and more SMS texts per person adds up.

Example 4 · The last moments of a GC log before OutOfMemoryError

Terminal
java -Xmx64m -Xlog:gc ErpBatchJob
Sample output
[0.008s][info][gc] Using G1
...
[0.512s][info][gc] GC(113) Pause Young (Concurrent Start) (G1 Evacuation Pause) 61M->59M(64M) 0.241ms
[0.515s][info][gc] GC(118) Pause Young (Concurrent Start) (G1 Evacuation Pause) 62M->60M(64M) 0.235ms
...
[0.584s][info][gc] GC(214) Pause Full (G1 Compaction Pause) 63M->62M(64M) 1.137ms
[0.584s][info][gc] GC(215) Concurrent Mark Cycle 1.186ms
[0.584s][info][gc] GC(216) Pause Young (Normal) (G1 Evacuation Pause) (Evacuation Failure) 63M->63M(64M) 0.187ms
[0.585s][info][gc] GC(217) Pause Full (G1 Compaction Pause) 63M->62M(64M) 1.002ms
[0.586s][info][gc] GC(218) Pause Young (Concurrent Start) (G1 Evacuation Pause) (Evacuation Failure) 63M->63M(64M) 0.224ms
[0.586s][info][gc] GC(220) Concurrent Mark Cycle
[0.587s][info][gc] GC(219) Pause Full (G1 Compaction Pause) 63M->62M(64M) 1.070ms
[0.589s][info][gc] GC(221) Pause Full (G1 Compaction Pause) 62M->60M(64M) 1.765ms
[0.589s][info][gc] GC(220) Concurrent Mark Cycle 2.901ms
[0.589s][info][gc] GC(222) Pause Young (Normal) (G1 Evacuation Pause) 60M->60M(64M) 0.208ms
[0.591s][info][gc] GC(223) Pause Full (G1 Compaction Pause) 60M->60M(64M) 1.258ms
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
...

What this code does

  • ErpBatchJob from the Taking a heap dump lesson, JDK 21, trimmed from about 300 GC lines (41 of them Pause Full). The heap after GC creeps from 59 to 60 MB of 64, then the full GCs start: each one frees 0 to 2 MB.
  • (Evacuation Failure) means G1 had no free space to copy surviving objects into. The last full GC frees nothing (60M->60M), and the next allocation fails. The pauses are tiny only because the heap is tiny; on a heap of several GB the same pattern means pauses of seconds.

Multiply that per-object cost by the number of objects you expect in a day, and you know whether it is a leak or simply a design that keeps too much. In a GC log, read three things on every pause line: the type (Pause Young, Pause Young (Mixed), Pause Full), the heap after GC (the number after the arrow) and the pause time. A tail of Pause Full lines that free 1 MB each, with (Evacuation Failure) in between, is G1 fighting for the last few megabytes: the heap is full of live objects.

Answer what to run next in short scenarios

Every scenario has one best next command, chosen by the question you need answered.

Example 5 · A next-step helper

NextStepDemo.javaJava
import java.util.List;
public class NextStepDemo {    static String nextStep(String symptom) {        String s = symptom.toLowerCase();        if (s.contains("which jvm") || s.contains("pid")) {            return "jps -l";        } else if (s.contains("flags") || s.contains("max heap")) {            return "jcmd <pid> VM.flags";        } else if (s.contains("grows") || s.contains("trend")) {            return "jstat -gcutil <pid> 10s";        } else if (s.contains("what fills") || s.contains("who holds")) {            return "jcmd <pid> GC.heap_dump /var/dumps/app.hprof";        } else if (s.contains("hang") || s.contains("threads")) {            return "jcmd <pid> Thread.print (three times)";        } else if (s.contains("last night") || s.contains("slow")) {            return "jcmd <pid> JFR.dump name=<rec> filename=app.jfr";        }        return "read the logs first";    }
    public static void main(String[] args) {        List<String> cases = List.of(            "Exam portal: which JVM is the results service?",            "Hostel app: what max heap did the JVM pick?",            "Online store: memory grows every hour",            "ERP job: what fills the old generation?",            "UPI service: requests hang, CPU idle",            "Booking site: slow for 10 minutes last night",            "Ticketing app: users say something is wrong");
        for (String c : cases) {            System.out.println(c);            System.out.println("  -> " + nextStep(c));        }    }}
Output
Exam portal: which JVM is the results service?
  -> jps -l
Hostel app: what max heap did the JVM pick?
  -> jcmd <pid> VM.flags
Online store: memory grows every hour
  -> jstat -gcutil <pid> 10s
ERP job: what fills the old generation?
  -> jcmd <pid> GC.heap_dump /var/dumps/app.hprof
UPI service: requests hang, CPU idle
  -> jcmd <pid> Thread.print (three times)
Booking site: slow for 10 minutes last night
  -> jcmd <pid> JFR.dump name=<rec> filename=app.jfr
Ticketing app: users say something is wrong
  -> read the logs first

What this code does

  • Each scenario is matched by the question it asks: which JVM, which settings, is it growing, what fills it, why does it hang, what happened before. The order of the checks matters: the first match wins.
  • The last case asks no clear question, so the answer is to observe first. Real diagnosis is the same: the question decides the tool, never the other way round.
  • "Which JVM?" → jps -l. "With which settings?" → jcmd <pid> VM.flags.
  • "Is memory growing?" → jstat -gcutil <pid> 10s or the GC log.
  • "What fills the heap, and who holds it?" → a class histogram, then jcmd <pid> GC.heap_dump.
  • "Why does it hang?" → three jcmd <pid> Thread.print a few seconds apart.
  • "What happened before?" → JFR.dump of a continuous recording.

If you do not know the question yet, you are still in the observe step: read the logs and the error message first.

Interview questions on heap dumps and JDK tools

Interviewers ask about this module in a few predictable ways. Prepare a two- or three-sentence answer for each:

  • How do you take a heap dump, and how do you get one automatically on OutOfMemoryError?
  • Shallow versus retained size, and how a dominator tree and paths to GC roots find a leak.
  • How do you tell a leak from a program that needs more memory?
  • What do jps, jcmd, jstat, jmap and jstack do, and which ones are older?
  • What is Java Flight Recorder and is it safe in production?
  • Which OutOfMemoryError messages exist, and why is more -Xmx not always the answer?

Good answers name the tool, the exact command and the evidence it gives. The Interview tab of this lesson has model answers.

Finish up

Mark complete & continue

Next: Case study: fix a program that runs out of heap