Skip to lesson

Taking a heap dump

jstat can tell you that memory is being kept; only a heap dump can tell you what is kept and who keeps it. A heap dump is a photograph of every object on the heap, saved to a file you can open and study after the program has moved on, or crashed.

jcmd GC.heap_dump: dump a running program

A heap dump is a snapshot of every object in the heap at one moment, used to find what is using memory and what keeps it alive.

A heap dump is a file that records every object on the heap: its class, its field values and the references between objects. HotSpot writes it in the HPROF format, usually with the extension .hprof.

Example 1 · Dump a running program with jcmd

Terminal
jcmd <pid> GC.heap_dump results.hprofjcmd <pid> GC.heap_dump results.hprofjcmd <pid> GC.heap_dump -gz=1 results2.hprof.gzls -l *.hprof*
Sample output
28264:
Dumping heap to results.hprof ...
Heap dump file created [32685702 bytes in 0.042 secs]

28264:
Dumping heap to results.hprof ...
Unable to create results.hprof: File exists

28264:
Dumping heap to results2.hprof.gz ...
Heap dump file created [1699361 bytes in 0.168 secs]

-rw-r--r-- 1 keert 197609 32685702 Oct 15 23:33 results.hprof
-rw-r--r-- 1 keert 197609  1699361 Oct 15 23:34 results2.hprof.gz

What this code does

  • The target is ResultsServer from the jps and jcmd lesson, about 30 seconds after start, on JDK 21. The dump of its roughly 30 MB of live objects took 0.042 seconds; on a heap of several GB expect seconds.
  • The second command fails: the JVM never overwrites an existing dump. Use a new name, or -overwrite on JDK 21.
  • The gzip dump is only 1.7 MB because the 20 KB marksheet arrays are full of zeros, which compress very well. Real data compresses less, but -gz=1 still saves a lot of disk and transfer time.

jcmd <pid> GC.heap_dump <file> asks a running JVM to write one. By default the JVM first runs a full GC and dumps only live (reachable) objects, which is what you want for leak hunting. The application pauses while the dump is written: a fraction of a second for a small heap, many seconds for a heap of several GB. The file is about as big as the used heap. The JVM itself writes the file, so a relative name is relative to the program's working folder, not yours; a full path avoids surprises. The JVM refuses to replace an existing file. Useful options in JDK 21: -gz=1 compresses the dump, -overwrite replaces an old file and -all keeps unreachable objects too.

Automatic dumps: -XX:+HeapDumpOnOutOfMemoryError

Many memory problems are found only after the crash, when the evidence is gone. -XX:+HeapDumpOnOutOfMemoryError tells the JVM to write a heap dump at the moment of the first OutOfMemoryError, while the heap is full of exactly the objects that caused it.

Terminal
java -Xmx2g -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/dumps -jar erp-batch.jar# turn it on later, without a restartjcmd <pid> VM.set_flag HeapDumpOnOutOfMemoryError truejcmd <pid> VM.set_flag HeapDumpPath /var/dumps

-XX:HeapDumpPath says where. If it names a folder, the file is called java_pid<pid>.hprof, so each crash gets its own file. If it names a file, that file is used. Make sure the folder exists and has free space at least as large as -Xmx, because a dump at OOM time is close to the full heap size.

Both flags cost nothing until an OOM happens, so most teams switch them on for every service. HeapDumpOnOutOfMemoryError is a manageable flag, which means you can even turn it on in a running JVM.

Example 2 · A batch job that will run out of heap

ErpBatchJob.javaJava
import java.util.ArrayList;import java.util.List;
public class ErpBatchJob {    // Bug: every audit record is kept for the whole run    static final List<byte[]> AUDIT_LOG = new ArrayList<>();
    static void recordAudit(int studentNo) {        AUDIT_LOG.add(new byte[50_000]);             // about 50 KB each    }
    static String buildReportCard(int studentNo) {        StringBuilder card = new StringBuilder();        for (int subject = 1; subject <= 5000; subject++) {            card.append("Student ").append(studentNo)                .append(" subject ").append(subject).append(": PASS\n");        }        return card.toString();    }
    public static void main(String[] args) {        for (int s = 1; s <= 3000; s++) {            recordAudit(s);            String card = buildReportCard(s);            if (s % 500 == 0) {                System.out.println("Processed " + s + " students, last card has " + card.length() + " chars");            }        }        System.out.println("Done");    }}
Output
Processed 500 students, last card has 153893 chars
Processed 1000 students, last card has 158893 chars
Processed 1500 students, last card has 158893 chars
Processed 2000 students, last card has 158893 chars
Processed 2500 students, last card has 158893 chars
Processed 3000 students, last card has 158893 chars
Done

What this code does

  • A college ERP batch job builds a report card for each student and, by mistake, keeps a 50 KB audit record for every one of them in a static list. Run plainly, it keeps about 150 MB and finishes in a couple of seconds.
  • On a server with a smaller heap, the same code fails. The next example runs it with a 64 MB heap and asks for an automatic heap dump.

Example 3 · Get the dump automatically at OutOfMemoryError

Terminal
mkdir dumpsjava -Xmx64m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=dumps ErpBatchJobls dumps
Sample output
Processed 500 students, last card has 153893 chars
Processed 1000 students, last card has 158893 chars
java.lang.OutOfMemoryError: Java heap space
Dumping heap to dumps\java_pid30116.hprof ...
Heap dump file created [65483664 bytes in 0.061 secs]
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at java.base/java.util.Arrays.copyOf(Arrays.java:3541)
	at java.base/java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:242)
	at java.base/java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:587)
	at java.base/java.lang.StringBuilder.append(StringBuilder.java:179)
	at ErpBatchJob.buildReportCard(ErpBatchJob.java:16)
	at ErpBatchJob.main(ErpBatchJob.java:24)

java_pid30116.hprof

What this code does

  • The JVM printed "Dumping heap to dumps\java_pid30116.hprof" before the usual stack trace (Windows shows a backslash). The dump is 65 MB, the size of the full 64 MB heap.
  • A second crash would write java_pid<new pid>.hprof next to it, because each run has a different pid. With -XX:HeapDumpPath=dumps/erp-batch.hprof (a file name) the JVM would refuse to replace an existing file.
  • The stack trace blames buildReportCard, not the audit list. The Reading an OutOfMemoryError message lesson explains why; the dump is how you find the real cause.

Fix the error

Fix the JVM option

Read the real error from java, then pick the line that fixes it.

Round 1 of 3

Dump the heap automatically when the heap is full.

# start the shop service
java -Xmx32m -XX:HeapDumpOnOutOfMemoryError Hog

Error

Missing +/- setting for VM option 'HeapDumpOnOutOfMemoryError'
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

jmap -dump: the older tool

jmap -dump:live,format=b,file=heap.hprof <pid> writes the same HPROF file. live runs a full GC and keeps only reachable objects; without it, jmap dumps every object including garbage. format=b means binary (HPROF), the only format today.

Example 4 · Dump and histogram with jmap

Terminal
jmap -dump:live,format=b,file=heap2.hprof <pid>jmap -histo:live <pid>
Sample output
Dumping heap to C:\...\diagnosing-memory-problems\heap2.hprof ...
Heap dump file created [32685702 bytes in 0.088 secs]

 num     #instances         #bytes  class name (module)
-------------------------------------------------------
   1:         11659       28536192  [B (java.base@21.0.7)
   2:          9486         227664  java.lang.String (java.base@21.0.7)
   3:           150         222840  [Ljdk.internal.vm.FillerElement; (java.base@21.0.7)
   4:          1111         137240  java.lang.Class (java.base@21.0.7)
   5:          1374         117456  [Ljava.lang.Object; (java.base@21.0.7)
   6:          2736          87552  java.util.concurrent.ConcurrentHashMap$Node (java.base@21.0.7)
...

What this code does

  • Same ResultsServer, same JDK 21. jmap prints the full path of the file it wrote (shortened here with ...), and the histogram has the same columns as GC.class_histogram.
  • Without :live, jmap -histo and jmap -dump include garbage that has not been collected yet, which makes a leak harder to see. Add live unless you have a reason not to.

jmap came before jcmd and you will meet it in older guides, scripts and interview questions. For new work, jcmd is the recommended single tool. jmap -histo:live <pid> prints the same class histogram as jcmd <pid> GC.class_histogram.

Heap dumps hold passwords and personal data

A heap dump contains every live object, so it contains every secret the program holds right now: passwords, OTPs, UPI PINs, API keys, database URLs, session tokens, and the names, phone numbers and marks of real users.

Example 5 · Search a dump for a secret

SecretInDumpDemo.javaJava
import com.sun.management.HotSpotDiagnosticMXBean;import java.lang.management.ManagementFactory;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;
class LoginSession {    final String phone;    final String upiPin;              // a secret kept in memory
    LoginSession(String phone, String upiPin) {        this.phone = phone;        this.upiPin = upiPin;    }}
public class SecretInDumpDemo {    static LoginSession current;
    static boolean contains(byte[] data, byte[] pattern) {        for (int i = 0; i + pattern.length <= data.length; i++) {            int j = 0;            while (j < pattern.length && data[i + j] == pattern[j]) {                j++;            }            if (j == pattern.length) {                return true;            }        }        return false;    }
    public static void main(String[] args) throws Exception {        current = new LoginSession("98xxxxxx01", "PIN-4821-SECRET");
        Path dir = Files.createTempDirectory("dump-demo");        Path dump = dir.resolve("wallet.hprof");        HotSpotDiagnosticMXBean bean =                ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);        bean.dumpHeap(dump.toString(), true);
        byte[] bytes = Files.readAllBytes(dump);        byte[] secret = "PIN-4821-SECRET".getBytes(StandardCharsets.ISO_8859_1);        System.out.println("Dump file: " + dump.getFileName());        System.out.println("Bigger than 1 MB: " + (bytes.length > 1_000_000));        System.out.println("Starts with: " + new String(bytes, 0, 12, StandardCharsets.US_ASCII));        System.out.println("UPI PIN found in dump: " + contains(bytes, secret));
        Files.delete(dump);        Files.delete(dir);        System.out.println("Session still in use for " + current.phone);    }}
Output
Dump file: wallet.hprof
Bigger than 1 MB: true
Starts with: JAVA PROFILE
UPI PIN found in dump: true
Session still in use for 98xxxxxx01

What this code does

  • HotSpotDiagnosticMXBean.dumpHeap(file, true) writes a live-objects dump from inside the program, the same as jcmd GC.heap_dump. The file name must end in .hprof and must not exist yet. Every HPROF file starts with the text JAVA PROFILE.
  • A plain byte search finds the UPI PIN. On Java 9 and later, a String with only Latin characters is stored as one byte per character, so the PIN sits in the file exactly as typed. No special tool is needed to steal it.
  • The program deletes the dump and its folder at the end. Do the same with real dumps once the problem is solved.

Anyone who has the file can read them with a text search. Treat a production dump like a database backup. Keep it on the server or in approved storage; never attach it to a public bug report, a chat group or an email. Restrict who can read the dump folder, compress it before moving it, share it only with the people debugging, and delete it when the investigation ends. Code can help too. Clear a char[] or byte[] that held a password once you are done with it (Arrays.fill), and do not keep secrets in long-lived caches or static fields.

A String cannot be cleared: it is immutable and may stay on the heap until GC removes it. That is why password APIs such as JPasswordField.getPassword() return a char[].

Next step

Check your understanding

11 quick questions