Skip to lesson

Reading a heap dump

A heap dump answers two questions: what fills the heap, and who keeps it there. Heap analysers such as Eclipse Memory Analyzer (MAT) and VisualVM read the .hprof file and give you a few views that answer exactly those questions; each view is built on one simple idea that you can compute by hand.

Class histogram: what takes the most space

The class histogram lists every class with its number of objects and their total shallow size, biggest first.

Example 1 · The histogram of the leaking results server

Terminal
jcmd <pid> GC.class_histogram
Sample output
28892:
 num     #instances         #bytes  class name (module)
-------------------------------------------------------
   1:          6905       42195296  [B (java.base@21.0.7)
   2:           153         309424  [Ljdk.internal.vm.FillerElement; (java.base@21.0.7)
   3:          4723         113352  java.lang.String (java.base@21.0.7)
   4:           730          91128  java.lang.Class (java.base@21.0.7)
   5:          1112          82232  [Ljava.lang.Object; (java.base@21.0.7)
   6:          2100          50400  Session
   7:          1251          40032  java.util.concurrent.ConcurrentHashMap$Node (java.base@21.0.7)
...
Total         23210       43160320

What this code does

  • ResultsServer (from the jps and jcmd lesson) 40 seconds after start, JDK 21. byte[] holds 42 MB, 98% of the heap, but byte[] is used everywhere, so it does not name the cause by itself.
  • The interesting row is Session: 2100 objects, only 50400 bytes shallow. 2100 is exactly 50 sessions per second for 42 seconds: nothing is ever removed. The next examples show why such a small class can explain the 42 MB of byte[].

It is the first view to open: MAT shows it as "Histogram" and VisualVM as the "Objects" or "Classes" view, and it has the same columns as jcmd <pid> GC.class_histogram. The top rows are almost always byte[], String, Object[] or HashMap$Node, because every program uses them. They tell you the shape of the memory, not the cause. Look further down for your own classes with suspicious counts: 2 million Session objects in an app with 500 users online, or as many OrderEvent objects as orders since the morning.

Shallow size versus retained size

Retained size is the memory that would be freed if an object were gone: the object itself plus everything that only it keeps alive. Shallow size is just the object's own header and fields.

The shallow size of an object is the memory of the object itself: its header and its fields. A field that refers to another object counts as one reference (usually 4 bytes on 64-bit HotSpot with compressed references), not as the object it points to.

Example 2 · Shallow and retained size, worked out by hand

RetainedSizeDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;import java.util.HashSet;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Set;
class HeapModel {    final Map<String, Integer> shallow = new LinkedHashMap<>();    final Map<String, List<String>> refs = new LinkedHashMap<>();    final List<String> roots;
    HeapModel(List<String> roots) {        this.roots = roots;    }
    void add(String name, int bytes, String... pointsTo) {        shallow.put(name, bytes);        refs.put(name, List.of(pointsTo));    }
    // Everything reachable from the GC roots, pretending 'removed' is not there    Set<String> reachable(String removed) {        Set<String> seen = new HashSet<>();        Deque<String> todo = new ArrayDeque<>();        for (String r : roots) {            if (!r.equals(removed)) {                todo.push(r);            }        }        while (!todo.isEmpty()) {            String o = todo.pop();            if (seen.add(o)) {                for (String next : refs.get(o)) {                    if (!next.equals(removed)) {                        todo.push(next);                    }                }            }        }        return seen;    }
    // Retained size: what the GC could free if this one object were gone    int retained(String object) {        Set<String> all = reachable(null);        Set<String> without = reachable(object);        int sum = 0;        for (String o : all) {            if (!without.contains(o)) {                sum += shallow.get(o);            }        }        return sum;    }}
public class RetainedSizeDemo {    public static void main(String[] args) {        // Approximate sizes on 64-bit HotSpot with compressed references        HeapModel heap = new HeapModel(List.of("ArrayList SESSIONS"));        heap.add("ArrayList SESSIONS", 24, "Object[] elementData");        heap.add("Object[] elementData", 56, "Session#1", "Session#2");        heap.add("Session#1", 24, "String roll#1", "byte[] pdf#1", "College");        heap.add("Session#2", 24, "String roll#2", "byte[] pdf#2", "College");        heap.add("String roll#1", 48);        heap.add("String roll#2", 48);        heap.add("byte[] pdf#1", 20016);        heap.add("byte[] pdf#2", 20016);        heap.add("College", 24);
        System.out.printf("%-22s %8s %9s%n", "Object", "Shallow", "Retained");        for (String o : heap.shallow.keySet()) {            System.out.printf("%-22s %8d %9d%n", o, heap.shallow.get(o), heap.retained(o));        }    }}
Output
Object                  Shallow  Retained
ArrayList SESSIONS           24     40280
Object[] elementData         56     40256
Session#1                    24     20088
Session#2                    24     20088
String roll#1                48        48
String roll#2                48        48
byte[] pdf#1              20016     20016
byte[] pdf#2              20016     20016
College                      24        24

What this code does

  • The program models a tiny heap: a list of two sessions, each with a roll-number string (counted together with its byte[]), a 20000-byte marksheet and a shared College. retained(x) finds everything reachable from the root, then everything reachable when x is removed, and adds up the difference.
  • Each Session is 24 bytes shallow but retains 20088 bytes: itself, its string and its marksheet. College is not in either session's retained size, because the other session still reaches it.
  • The list retains 40280 bytes: everything. In a real dump this is the line that says "this one list keeps 40 MB alive".

The retained size of an object is the memory the GC could free if that object were gone: the object itself plus everything that is reachable only through it. An object that is also reachable another way, such as a shared College object, is not part of anyone's retained size. That is why a histogram can mislead. A Session is 24 bytes shallow, so 2000 sessions look like 48 KB; but each one retains a 20 KB marksheet, so together they keep about 40 MB alive. Leaks are found by retained size.

The byte sizes in this lesson's models are approximate, for 64-bit HotSpot with compressed references (the usual setting for heaps under 32 GB). Real tools read the exact sizes from the dump.

Dominators and the biggest retained objects

Object A dominates object B when every path from the GC roots to B goes through A. Remove A and B becomes unreachable, so B is part of A's retained size. The immediate dominator of B is the closest such A.

Example 3 · A dominator tree, built by hand

DominatorTreeDemo.javaJava
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Comparator;import java.util.Deque;import java.util.HashSet;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Set;
class ObjectGraph {    final Map<String, Integer> shallow = new LinkedHashMap<>();    final Map<String, List<String>> refs = new LinkedHashMap<>();    final List<String> roots;
    ObjectGraph(List<String> roots) {        this.roots = roots;    }
    void add(String name, int bytes, String... pointsTo) {        shallow.put(name, bytes);        refs.put(name, List.of(pointsTo));    }
    Set<String> reachable(String removed) {        Set<String> seen = new HashSet<>();        Deque<String> todo = new ArrayDeque<>();        roots.stream().filter(r -> !r.equals(removed)).forEach(todo::push);        while (!todo.isEmpty()) {            String o = todo.pop();            if (seen.add(o)) {                refs.get(o).stream().filter(n -> !n.equals(removed)).forEach(todo::push);            }        }        return seen;    }
    Set<String> dominatedBy(String x) {        Set<String> gone = new HashSet<>(reachable(null));        gone.removeAll(reachable(x));        return gone;    }
    int retained(String x) {        return dominatedBy(x).stream().mapToInt(shallow::get).sum();    }
    // The closest object that every path from the roots to 'y' must pass through    String immediateDominator(String y) {        String best = null;        for (String x : shallow.keySet()) {            if (!x.equals(y) && dominatedBy(x).contains(y)                    && (best == null || dominatedBy(x).size() < dominatedBy(best).size())) {                best = x;            }        }        return best;    }
    void printTree(String node, String indent) {        System.out.printf("%-30s retained %6d%n", indent + node, retained(node));        List<String> children = new ArrayList<>();        for (String o : shallow.keySet()) {            if (node.equals(immediateDominator(o))) {                children.add(o);            }        }        children.sort(Comparator.comparingInt(this::retained).reversed()                .thenComparing(Comparator.naturalOrder()));        for (String c : children) {            printTree(c, indent + "  ");        }    }}
public class DominatorTreeDemo {    public static void main(String[] args) {        // Approximate sizes; a String is counted together with its byte[]        ObjectGraph heap = new ObjectGraph(List.of("ArrayList SESSIONS", "AppConfig CONFIG"));        heap.add("ArrayList SESSIONS", 24, "Object[] elementData");        heap.add("Object[] elementData", 56, "Session#1", "Session#2", "Session#3");        heap.add("Session#1", 24, "String roll#1", "byte[] pdf#1", "College");        heap.add("Session#2", 24, "String roll#2", "byte[] pdf#2", "College");        heap.add("Session#3", 24, "String roll#3", "byte[] pdf#3", "College");        heap.add("String roll#1", 48);        heap.add("String roll#2", 48);        heap.add("String roll#3", 48);        heap.add("byte[] pdf#1", 20016);        heap.add("byte[] pdf#2", 20016);        heap.add("byte[] pdf#3", 20016);        heap.add("College", 24, "String collegeName");        heap.add("String collegeName", 56);        heap.add("AppConfig CONFIG", 16, "College");
        // Top level: objects that no single other object dominates        List<String> top = new ArrayList<>();        for (String o : heap.shallow.keySet()) {            if (heap.immediateDominator(o) == null) {                top.add(o);            }        }        top.sort(Comparator.comparingInt(heap::retained).reversed());        for (String o : top) {            heap.printTree(o, "");        }    }}
Output
ArrayList SESSIONS             retained  60344
  Object[] elementData         retained  60320
    Session#1                  retained  20088
      byte[] pdf#1             retained  20016
      String roll#1            retained     48
    Session#2                  retained  20088
      byte[] pdf#2             retained  20016
      String roll#2            retained     48
    Session#3                  retained  20088
      byte[] pdf#3             retained  20016
      String roll#3            retained     48
College                        retained     80
  String collegeName           retained     56
AppConfig CONFIG               retained     16

What this code does

  • dominatedBy(x) is the set of objects that become unreachable without x. The immediate dominator of y is the object with the smallest such set that still contains y. Each object is printed under its immediate dominator, biggest retained size first.
  • College is reachable from every session and from AppConfig, so no single object dominates it: it moves to the top level with its name string. This is the same shape a heap analyser shows, only with thousands of objects instead of fourteen.
  • The top of the tree is the answer to "what keeps the most memory alive": ArrayList SESSIONS. In MAT, the Leak Suspects report would point at it in its first paragraph.

The dominator tree puts every object under its immediate dominator, and sorts each level by retained size. Its top entries are the objects that keep the most memory alive, which is usually where a leak sits: one ArrayList, HashMap or cache holding gigabytes. MAT's "Leak Suspects" report, which opens with a dump, is built from this tree. An object reachable from two different places, such as a configuration object used by every session, has no single dominator inside the tree; it appears near the top on its own.

Path to GC roots: who is holding this object

A path to GC roots is the chain of references from a GC root, such as a static field or a thread stack, down to an object. It shows why the object is still alive.

Once you know what is big, you need to know why it is still alive. A path to GC roots is the chain of references from a GC root (a static field, a live thread's local variable, a JNI reference) down to the object.

A path to GC roots: the static field ACTIVE_CARTS (a GC root) holds a HashMap (retained 96 MB), which holds Cart objects (retained 2 MB each), which hold byte[] photos (2 MB). Cut the static field and the whole chain can be freed.

Example 4 · Follow the path from a leaking object to its GC root

PathToRootDemo.javaJava
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Deque;import java.util.HashMap;import java.util.List;import java.util.Map;
record Ref(String from, String field, String to) { }
public class PathToRootDemo {    static final String ROOT = "class ResultsServer";
    // A model of the leaking heap: who points to whom, and through which field    static final List<Ref> REFS = List.of(            new Ref(ROOT, "static SESSIONS", "ArrayList@1"),            new Ref("ArrayList@1", "elementData", "Object[]@2"),            new Ref("Object[]@2", "[0]", "Session@3"),            new Ref("Object[]@2", "[1]", "Session@4"),            new Ref("Session@3", "rollNo", "String@5"),            new Ref("Session@3", "marksheetPdf", "byte[]@6"),            new Ref("Session@4", "rollNo", "String@7"),            new Ref("Session@4", "marksheetPdf", "byte[]@8"));
    static List<String> pathToRoot(String target) {        Map<String, Ref> cameFrom = new HashMap<>();        Deque<String> queue = new ArrayDeque<>(List.of(ROOT));        while (!queue.isEmpty()) {                       // breadth-first search from the root            String current = queue.poll();            for (Ref r : REFS) {                if (r.from().equals(current) && !cameFrom.containsKey(r.to())) {                    cameFrom.put(r.to(), r);                    queue.add(r.to());                }            }        }        List<String> lines = new ArrayList<>();        lines.add(target);        String at = target;        while (cameFrom.containsKey(at)) {               // walk back towards the root            Ref r = cameFrom.get(at);            lines.add("  <- " + r.field() + " of " + r.from());            at = r.from();        }        lines.add("     (" + at + " is a GC root)");        return lines;    }
    public static void main(String[] args) {        System.out.println("Why is byte[]@8 still alive?");        pathToRoot("byte[]@8").forEach(System.out::println);    }}
Output
Why is byte[]@8 still alive?
byte[]@8
  <- marksheetPdf of Session@4
  <- [1] of Object[]@2
  <- elementData of ArrayList@1
  <- static SESSIONS of class ResultsServer
     (class ResultsServer is a GC root)

What this code does

  • Each Ref is one reference: from an object, through a field, to an object. A breadth-first search from the root remembers how each object was first reached, then the program walks back from the target to the root.
  • This is the same chain a heap analyser prints for "Path To GC Roots": array slot [1] of the list's internal array, the list in field elementData, the list in the static field SESSIONS. A class loaded by the application class loader stays loaded, so its static fields act as GC roots.
  • The line next to the root names the place to fix: ResultsServer.SESSIONS.

In MAT: right-click the object, "Path To GC Roots", and choose to exclude weak and soft references, because those do not keep an object alive. Read the path from the bottom up: the last line is the root, and the line just above it usually names the field to fix. "static SESSIONS of class ResultsServer" says the leak is a static list that is never cleared. The fix is a code change there: remove entries, bound the collection, or stop keeping the objects at all.

Find the bug

Find the line that keeps the objects

A heap dump points at a static field. Tap the line that keeps the objects alive, then check the fix.

The path to GC roots ends at ACTIVE.

Round 1 of 3
If an object has several paths to roots, fixing one is not enough: it stays alive until the last strong path is gone.

Comparing two dumps taken some time apart

One dump shows a moment; a leak is a trend. Take two dumps (or two class histograms) a few minutes apart, under similar load, and compare the instance counts per class. Normal objects go up and down; leaking ones only grow.

Example 5 · Two histograms, 30 seconds apart

Terminal
jcmd <pid> GC.class_histogram > histo-1.txt# wait 30 secondsjcmd <pid> GC.class_histogram > histo-2.txt
Sample output
histo-1.txt (about 10 s after start):
   1:          3805       11133296  [B (java.base@21.0.7)
   2:           732          91360  java.lang.Class (java.base@21.0.7)
   3:          3173          76152  java.lang.String (java.base@21.0.7)
   4:          1112          74424  [Ljava.lang.Object; (java.base@21.0.7)
...
  11:           550          13200  Session

histo-2.txt (30 s later):
   1:          6905       42195296  [B (java.base@21.0.7)
...
   3:          4723         113352  java.lang.String (java.base@21.0.7)
   4:           730          91128  java.lang.Class (java.base@21.0.7)
   5:          1112          82232  [Ljava.lang.Object; (java.base@21.0.7)
   6:          2100          50400  Session

What this code does

  • Both files come from the same ResultsServer run on JDK 21 (trimmed to the rows that matter). Saving histograms to files makes them easy to compare later.
  • Session moved from rank 11 to rank 6 and its count nearly quadrupled. java.lang.Class stayed at about 730: no new classes are loaded, so this is not a class or metaspace problem.

Example 6 · Diff the two histograms

HistogramDiffDemo.javaJava
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
public class HistogramDiffDemo {    // Lines from two real class histograms of ResultsServer, taken 30 seconds apart    static final String[] FIRST = {        "   1:          3805       11133296  [B (java.base@21.0.7)",        "   2:           732          91360  java.lang.Class (java.base@21.0.7)",        "   3:          3173          76152  java.lang.String (java.base@21.0.7)",        "   4:          1112          74424  [Ljava.lang.Object; (java.base@21.0.7)",        "  11:           550          13200  Session"    };    static final String[] SECOND = {        "   1:          6905       42195296  [B (java.base@21.0.7)",        "   3:          4723         113352  java.lang.String (java.base@21.0.7)",        "   4:           730          91128  java.lang.Class (java.base@21.0.7)",        "   5:          1112          82232  [Ljava.lang.Object; (java.base@21.0.7)",        "   6:          2100          50400  Session"    };
    static Map<String, long[]> parse(String[] lines) {        Map<String, long[]> byClass = new HashMap<>();        for (String line : lines) {            String[] p = line.trim().split("\\s+");            byClass.put(p[3], new long[] {Long.parseLong(p[1]), Long.parseLong(p[2])});        }        return byClass;    }
    public static void main(String[] args) {        Map<String, long[]> before = parse(FIRST);        Map<String, long[]> after = parse(SECOND);
        List<String> rows = new ArrayList<>();        for (String cls : after.keySet()) {            long[] a = after.get(cls);            long[] b = before.getOrDefault(cls, new long[] {0, 0});            long moreObjects = a[0] - b[0];            long moreBytes = a[1] - b[1];            if (moreObjects > 0) {                rows.add(String.format("%-18s %+7d objects %+11d bytes", cls, moreObjects, moreBytes));            }        }        rows.sort(null);        System.out.println("Grew in 30 seconds:");        rows.forEach(System.out::println);    }}
Output
Grew in 30 seconds:
Session              +1550 objects      +37200 bytes
[B                   +3100 objects   +31062000 bytes
java.lang.String     +1550 objects      +37200 bytes

What this code does

  • The program parses the real lines from both files and prints only the classes whose instance count grew. Class and Object[] did not, so they are not listed.
  • 1550 more sessions, 1550 more strings (one roll number each) and 3100 more byte[] (one marksheet plus one string's characters each): everything grows in step with Session. That points at the sessions as the leaking unit, and the path to GC roots tells you who keeps them.

Look for classes that grow together. If Session grew by 1550, String by 1550 and byte[] by 3100, then every new session brought one string and two byte arrays with it: the session is the leaking unit, and the others are just its luggage. MAT can compare two histograms directly; for histograms in text form, a small program does it, as the last example shows.

Next step

Check your understanding

12 quick questions