Skip to lesson

A step-by-step diagnosis workflow

Memory problems feel scary because the symptoms are vague: "the site is slow", "it crashed at night". A fixed routine turns them into facts. Observe, measure, capture, fix and verify: every tool in this module has its place in one of those four steps.

Observe: symptoms, logs and error messages

Observing means collecting what already happened before you touch anything. Write down the symptoms in plain words (slow pages, timeouts, crashes, restarts), when they started, and what changed around that time: a deploy, a traffic spike, a new feature, a config change.

The diagnosis workflow in five steps: 1 Observe (logs, error text), 2 Measure (jstat, GC log), 3 Capture (jcmd dumps, flight recording), 4 Fix (change one thing), 5 Verify (repeat the same measurement).

Example 1 · Build one timeline from scattered log lines

IncidentTimelineDemo.javaJava
import java.util.ArrayList;import java.util.List;
record LogLine(String time, String level, String text) {    static LogLine parse(String line) {        String[] p = line.split(" ", 3);        return new LogLine(p[0], p[1], p[2]);    }}
public class IncidentTimelineDemo {    public static void main(String[] args) {        // Log lines collected from two servers of an exam-results site        List<String> raw = List.of(            "09:58:02 INFO Results published for semester 5",            "10:01:10 WARN Response time 2.1 s (normal 0.2 s)",            "10:00:00 INFO Deploy v4.2: new 'download marksheet' feature",            "10:07:45 WARN Response time 6.8 s",            "10:12:30 ERROR java.lang.OutOfMemoryError: Java heap space",            "10:12:31 INFO Server 2 restarted by supervisor",            "09:40:00 INFO Normal traffic: 300 users online",            "10:05:00 INFO Traffic: 9000 users online");
        List<LogLine> lines = new ArrayList<>();        for (String r : raw) {            lines.add(LogLine.parse(r));        }        lines.sort((a, b) -> a.time().compareTo(b.time()));   // HH:mm:ss sorts as text
        System.out.println("Timeline:");        for (LogLine l : lines) {            String mark = l.level().equals("INFO") ? "  " : "! ";            System.out.println(mark + l.time() + " " + l.text());        }        long problems = lines.stream().filter(l -> !l.level().equals("INFO")).count();        System.out.println("Warnings and errors: " + problems                + ", first at " + lines.stream().filter(l -> !l.level().equals("INFO"))                        .findFirst().map(LogLine::time).orElse("-"));    }}
Output
Timeline:
  09:40:00 Normal traffic: 300 users online
  09:58:02 Results published for semester 5
  10:00:00 Deploy v4.2: new 'download marksheet' feature
! 10:01:10 Response time 2.1 s (normal 0.2 s)
  10:05:00 Traffic: 9000 users online
! 10:07:45 Response time 6.8 s
! 10:12:30 java.lang.OutOfMemoryError: Java heap space
  10:12:31 Server 2 restarted by supervisor
Warnings and errors: 3, first at 10:01:10

What this code does

  • Lines from two servers arrive in any order. Sorting by time (text sort works for HH:mm:ss) and marking warnings and errors with ! gives the story: results published, a deploy at 10:00, slow responses from 10:01, then OOM and a restart at 10:12.
  • Two suspects appear at once: the deploy with a new marksheet feature and the 30× traffic jump. The next step, measuring, decides which one matters: does heap after GC keep rising even when traffic is steady?

Then read the logs. An OutOfMemoryError message names the memory area (the Reading an OutOfMemoryError message lesson); a restart by the supervisor tells you the JVM died; rising response times before the error tell you the problem built up slowly. Put everything on one timeline, from all servers, sorted by time. Do not restart a struggling JVM before you have captured evidence, unless users are badly affected. A restart makes the symptoms disappear for a few hours and takes the evidence with it.

Measure: GC logs, jstat and jcmd

Measuring turns "it feels slow" into numbers. The three questions are: is the heap after GC rising, how much time goes to GC, and how long are the pauses?

Example 2 · Measure: the GC log of the leaking server

Terminal
java -Xms256m -Xmx256m -Xlog:gc:file=gc-leak.log ResultsServercat gc-leak.log
Sample output
[0.016s][info][gc] Using G1
[2.264s][info][gc] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 23M->2M(256M) 16.794ms
[5.335s][info][gc] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 36M->6M(256M) 2.777ms
[20.615s][info][gc] GC(2) Pause Young (Normal) (G1 Evacuation Pause) 146M->20M(256M) 10.381ms
[35.145s][info][gc] GC(3) Pause Young (Normal) (G1 Evacuation Pause) 155M->34M(256M) 17.875ms
[50.655s][info][gc] GC(4) Pause Young (Normal) (G1 Evacuation Pause) 173M->48M(256M) 18.662ms
[66.276s][info][gc] GC(5) Pause Young (Normal) (G1 Evacuation Pause) 186M->62M(256M) 22.484ms
[80.757s][info][gc] GC(6) Pause Young (Normal) (G1 Evacuation Pause) 200M->76M(256M) 20.501ms

What this code does

  • ResultsServer from this module, 90 seconds with a fixed 256 MB heap on JDK 21. In 23M->2M(256M), 23 MB was used before the pause, 2 MB after, and the heap is 256 MB.
  • The number after the arrow climbs at every collection: 2, 6, 20, 34, 48, 62, 76 MB. Pauses stay short (under 23 ms), so GC itself is not the problem yet; kept objects are. This is the same story jstat told in the jstat lesson, from a different tool.

Example 3 · Turn GC log lines into a verdict

GcLogTrendDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.regex.Matcher;import java.util.regex.Pattern;
public class GcLogTrendDemo {    // "23M->2M(256M)": heap before GC -> heap after GC (heap size)    static final Pattern HEAP = Pattern.compile("(\\d+)M->(\\d+)M\\((\\d+)M\\)");
    static List<Integer> afterGc(List<String> log) {        List<Integer> after = new ArrayList<>();        for (String line : log) {            Matcher m = HEAP.matcher(line);            if (line.contains("Pause") && m.find()) {                after.add(Integer.parseInt(m.group(2)));            }        }        return after;    }
    static void report(String name, List<String> log) {        List<Integer> after = afterGc(log);        int first = after.get(0);        int last = after.get(after.size() - 1);        System.out.println(name + ": heap after GC " + after);        System.out.println("  grew by " + (last - first) + " MB over " + after.size() + " collections"                + (last > first * 3 ? " -> keeps growing, suspect a leak" : " -> stable"));    }
    public static void main(String[] args) {        // Real -Xlog:gc lines (JDK 21, G1, -Xms256m -Xmx256m)        List<String> before = List.of(            "[2.264s][info][gc] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 23M->2M(256M) 16.794ms",            "[5.335s][info][gc] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 36M->6M(256M) 2.777ms",            "[20.615s][info][gc] GC(2) Pause Young (Normal) (G1 Evacuation Pause) 146M->20M(256M) 10.381ms",            "[35.145s][info][gc] GC(3) Pause Young (Normal) (G1 Evacuation Pause) 155M->34M(256M) 17.875ms",            "[50.655s][info][gc] GC(4) Pause Young (Normal) (G1 Evacuation Pause) 173M->48M(256M) 18.662ms",            "[66.276s][info][gc] GC(5) Pause Young (Normal) (G1 Evacuation Pause) 186M->62M(256M) 22.484ms",            "[80.757s][info][gc] GC(6) Pause Young (Normal) (G1 Evacuation Pause) 200M->76M(256M) 20.501ms");        List<String> after = List.of(            "[2.237s][info][gc] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 23M->2M(256M) 2.416ms",            "[5.302s][info][gc] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 35M->4M(256M) 2.837ms",            "[20.543s][info][gc] GC(2) Pause Young (Normal) (G1 Evacuation Pause) 145M->5M(256M) 3.417ms",            "[36.997s][info][gc] GC(3) Pause Young (Normal) (G1 Evacuation Pause) 154M->5M(256M) 4.324ms",            "[53.538s][info][gc] GC(4) Pause Young (Normal) (G1 Evacuation Pause) 154M->5M(256M) 6.309ms",            "[69.272s][info][gc] GC(5) Pause Young (Normal) (G1 Evacuation Pause) 154M->5M(256M) 5.508ms",            "[85.810s][info][gc] GC(6) Pause Young (Normal) (G1 Evacuation Pause) 154M->5M(256M) 4.873ms");
        report("Before the fix", before);        report("After the fix", after);    }}
Output
Before the fix: heap after GC [2, 6, 20, 34, 48, 62, 76]
  grew by 74 MB over 7 collections -> keeps growing, suspect a leak
After the fix: heap after GC [2, 4, 5, 5, 5, 5, 5]
  grew by 3 MB over 7 collections -> stable

What this code does

  • A regular expression pulls before->after(size) out of each pause line; group 2 is the heap after GC. Both lists are real -Xlog:gc lines: the leaking ResultsServer and the fixed HealthyServer, same flags, same 90 seconds.
  • The "more than 3 times the first value" rule is only a quick check for this lesson. Real monitoring compares the lowest heap after GC over hours or days.
  • GC log (-Xlog:gc on Java 9 and later): every collection with heap before, after and pause time. The best evidence, if it was switched on before the problem.
  • jstat -gcutil <pid> 10s: the same trend live, cheaply, when there is no log.
  • jcmd <pid> GC.heap_info and VM.flags: the real heap size and collector, so you compare numbers with the right limits. Rising heap after GC means objects are being kept: think leak or too much live data. Stable heap after GC with long or frequent pauses means allocation pressure or a GC setting problem. Stable heap with normal GC means the cause is probably not memory at all: look at threads, locks, the database or the network.

Capture: heap dumps, thread dumps and recordings

Capturing saves the evidence you need to find the cause, ideally before a restart. You pick what to capture by the symptom.

Example 4 · Capture: the evidence kit, cheap things first

Terminal
jcmd <pid> GC.heap_infojcmd <pid> GC.class_histogram | head -14jcmd <pid> Thread.print -l > threads-1.txtjcmd <pid> JFR.start name=incident maxsize=100m# ... a few minutes laterjcmd <pid> JFR.dump name=incident filename=incident.jfrjcmd <pid> GC.heap_dump incident.hprof
Sample output
26292:
 garbage-first heap   total 120832K, used 37997K [0x000000008a600000, 0x0000000100000000)
  region size 1024K, 25 young (25600K), 7 survivors (7168K)
 Metaspace       used 333K, committed 512K, reserved 1114112K
  class space    used 21K, committed 128K, reserved 1048576K
26292:
 num     #instances         #bytes  class name (module)
-------------------------------------------------------
   1:          4803       21153240  [B (java.base@21.0.7)
   2:            97         191168  [Ljdk.internal.vm.FillerElement; (java.base@21.0.7)
   3:           732          91360  java.lang.Class (java.base@21.0.7)
   4:          3671          88104  java.lang.String (java.base@21.0.7)
   5:          1112          76064  [Ljava.lang.Object; (java.base@21.0.7)
   6:          1251          40032  java.util.concurrent.ConcurrentHashMap$Node (java.base@21.0.7)
   7:            11          37704  [C (java.base@21.0.7)
   8:           895          28640  java.util.HashMap$Node (java.base@21.0.7)
   9:          1050          25200  Session
  10:           217          20752  [Ljava.util.HashMap$Node; (java.base@21.0.7)
  11:            20          15168  [Ljava.util.concurrent.ConcurrentHashMap$Node; (java.base@21.0.7)
26292:
Started recording 1.

Use jcmd 26292 JFR.dump name=incident filename=FILEPATH to copy recording data to file.
26292:
Dumped recording "incident", 266.4 kB written to:

C:\...\incident.jfr
26292:
Dumping heap to incident.hprof ...
Heap dump file created [39903494 bytes in 0.034 secs]

What this code does

  • One real capture of ResultsServer on JDK 21, about 20 seconds after start (the recording ran 10 seconds). The thread dump went to a file, so it printed nothing. Take two more a few seconds later if threads are the suspect.
  • In about half a minute you have a heap summary, a histogram (1050 Session objects already), a thread dump, a flight recording and a 40 MB heap dump. After that, a restart is safe: the evidence is on disk.
  • Heap after GC rising, or an OutOfMemoryError: Java heap space → a heap dump (or two, some minutes apart), plus class histograms.
  • Hangs, timeouts, too many threads → three thread dumps a few seconds apart.
  • Slow but no clear signal, or "what happened before" → a flight recording; dump a continuous one with JFR.dump.

Capture the cheap things first (GC.heap_info, histograms, thread dumps, JFR.dump), and the heap dump last, because it pauses the application. Keep every file with the time and server name, and treat dumps and recordings as sensitive data.

Fix one cause and verify with the same measurements

Find the cause in the evidence: the dominator tree and path to GC roots for a leak, the deadlock report for a hang, the hot methods for CPU. Then change one thing.

Java
// The fix in HealthyServer (one change): never keep more than 200 sessionsSESSIONS.add(new Session("22CS" + (second * 100 + visit)));if (SESSIONS.size() > 200) SESSIONS.remove(0);

If you change the code, the heap size and the collector together, you will not know which one helped.

Verify with exactly the same measurement that showed the problem: the same test, the same flags, the same jstat or GC log. "Heap after GC rose from 2 MB to 76 MB in 90 seconds; after the fix it stays at 5 MB" is proof. "It seems faster" is not. Then explain it to your team lead in a few lines: symptom (what users saw and when), evidence (the numbers and the dump finding), cause (the code), fix, and verification. Add one line on how to catch it earlier next time, such as an alert on heap after GC.

Example 5 · Verify: the same GC log, before and after the fix

Terminal
java -Xms256m -Xmx256m -Xlog:gc:file=gc-healthy.log HealthyServercat gc-healthy.log
Sample output
[0.014s][info][gc] Using G1
[2.237s][info][gc] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 23M->2M(256M) 2.416ms
[5.302s][info][gc] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 35M->4M(256M) 2.837ms
[20.543s][info][gc] GC(2) Pause Young (Normal) (G1 Evacuation Pause) 145M->5M(256M) 3.417ms
[36.997s][info][gc] GC(3) Pause Young (Normal) (G1 Evacuation Pause) 154M->5M(256M) 4.324ms
[53.538s][info][gc] GC(4) Pause Young (Normal) (G1 Evacuation Pause) 154M->5M(256M) 6.309ms
[69.272s][info][gc] GC(5) Pause Young (Normal) (G1 Evacuation Pause) 154M->5M(256M) 5.508ms
[85.810s][info][gc] GC(6) Pause Young (Normal) (G1 Evacuation Pause) 154M->5M(256M) 4.873ms

What this code does

  • HealthyServer has exactly one change, the one shown above, and ran with the same flags for the same 90 seconds. Heap after GC settles at 5 MB, against 76 MB and rising before the fix.
  • The pauses also got shorter (2 to 6 ms instead of up to 22 ms), because G1 has fewer live objects to copy. Same test, same numbers, one change: that is a verified fix.

Example 6 · A better fix: a bounded session store

SessionStoreFixDemo.javaJava
import java.util.LinkedHashMap;import java.util.Map;
class SessionStore {    private static final int MAX_SESSIONS = 200;
    // access order + removeEldestEntry = a small LRU cache    private final Map<String, byte[]> sessions = new LinkedHashMap<>(256, 0.75f, true) {        @Override        protected boolean removeEldestEntry(Map.Entry<String, byte[]> eldest) {            return size() > MAX_SESSIONS;        }    };
    void open(String rollNo) {        sessions.put(rollNo, new byte[20_000]);    }
    void close(String rollNo) {        sessions.remove(rollNo);    }
    int size() {        return sessions.size();    }}
public class SessionStoreFixDemo {    public static void main(String[] args) {        SessionStore store = new SessionStore();        for (int visit = 1; visit <= 4500; visit++) {            String roll = "22CS" + visit;            store.open(roll);            if (visit % 3 == 1) {                store.close(roll);                  // students who log out free their session            }        }        System.out.println("Visits: 4500");        System.out.println("Sessions kept: " + store.size());        System.out.println("Memory held by sessions: about " + store.size() * 20 + " KB");    }}
Output
Visits: 4500
Sessions kept: 200
Memory held by sessions: about 4000 KB

What this code does

  • HealthyServer's remove(0) on an ArrayList works but copies the list each time. A LinkedHashMap in access order with removeEldestEntry is a small LRU cache: it drops the least recently used session once there are more than 200.
  • Sessions are also removed when a student logs out (close). 4500 visits now keep exactly 200 sessions, about 4 MB, however long the server runs. Verify it the same way: heap after GC must settle.

Order of execution

Put the diagnosis steps in order

An online store gets slower every afternoon. Tap the steps in the order you would do them.

Next step

Check your understanding

12 quick questions