How to Take a Java Heap Dump: Every Method and Option

jcmd, jmap, dump on OutOfMemoryError, MXBean, Actuator and Kubernetes, with every JDK 17 option, the measured pause and file size, and what each file leaks.

By · · 12 min read

Illustration for How to Take a Java Heap Dump: Every Method and Option

The service's memory graph only climbs, the next OutOfMemoryError is an hour away, and you need the heap on disk before anyone restarts the pod. On any HotSpot JDK from 8 onwards the answer is one command: jcmd <pid> GC.heap_dump /path/heap.hprof, which forces a full GC and writes the live objects as an HPROF file. For the crash you cannot catch by hand, start the JVM with -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=<directory>. Everything below was run on OpenJDK 17.0.21.1; the options listed are JDK 17's unless a later version is named, and once the file exists the Java Heap Dump Analyzer reads it in your browser without uploading it.

Find the process first

Every live method needs the JVM's process id. jcmd -l lists the JVMs your user can attach to, with the main class and arguments; jps -l prints the same with fully qualified names:

$ jcmd -l
48098 jdk.jcmd/sun.tools.jcmd.JCmd -l
48076 OrderService 200

The jcmd manual requires the same machine and the same effective user and group as the target JVM, so a JVM started by appuser is invisible to root's jcmd. A main class name works in place of the pid, but the manual says it targets every JVM whose main class matches, so use the pid when two copies share a host. In a container where the JVM is the entrypoint, the pid is usually 1.

jcmd GC.heap_dump: the default choice

Ask the running JVM what it supports: Oracle's JDK 17 jcmd page lists only -all, but the 17.0.21 VM answers with three options, and this guide follows the VM, since that is the code that runs:

$ jcmd 48076 help GC.heap_dump
Impact: High: Depends on Java heap size and content. Request a full GC unless the '-all' option is specified.
Syntax : GC.heap_dump [options] <filename>
Options: (options must be specified using the <key> or <key>=<value> syntax)
	-all : [optional] Dump all objects, including unreachable objects (BOOLEAN, false)
	-gz : [optional] If specified, the heap dump is written in gzipped format using the given compression level. 1 (recommended) is the fastest, 9 the strongest compression. (INT, 1)
	-overwrite : [optional] If specified, the dump file will be overwritten if it exists (BOOLEAN, false)
OptionWhat it doesMeasured on 17.0.21.1
(none)Full GC first, then only reachable objectsLog shows Pause Full (Heap Dump Initiated GC)
-allNo GC; unreachable garbage is written tooNo Full GC line; file includes dead objects
-gz=1 to -gz=9Gzip while writing-gz 1 (space) and a bare -gz both fail with Integer parsing error; -gz=0 and -gz=10 fail with Compression level out of range (1-9)
-overwriteReplace an existing fileWithout it: Unable to create ...: File exists

Three behaviours the help does not mention. A relative filename is resolved against the target JVM's working directory, not your shell's: jcmd 48076 GC.heap_dump relative.hprof landed next to the service. Every dump was created with mode -rw-------, readable only by the JVM's user. And the time jcmd prints (Heap dump file created [2690498695 bytes in 4.792 secs]) matched the JVM's own safepoint log to the millisecond, full GC included, so that figure is how long your application was frozen.

Newer JDKs add two options, confirmed in Oracle's manual pages: -parallel=<n> for multi-threaded dumping appears in the JDK 22 jcmd page, and %p in the filename expanding to the pid appears from the JDK 24 page. Neither works on 17.

jmap -dump: same file, opposite default

jmap -dump:live,format=b,file=/tmp/heap.hprof 48076

live triggers the full GC and keeps reachable objects; format=b asks for binary HPROF; file= names the output. The 17 binary's jmap -help also lists all and gz=<1-9>, which its manual page omits. The trap is the default: jmap's own help says all is the default when neither is given, the opposite of jcmd, so jmap -dump:file=... writes garbage too. In testing, leaving out format=b still produced a binary file starting JAVA PROFILE 1.0.2, but keep it for scripts that must also run on JDK 8. jmap has no overwrite switch and refuses an existing file. Its JDK 17 manual calls it "experimental and unsupported", which is the reason to prefer jcmd.

Dump automatically on OutOfMemoryError

The dump you most want is the one taken at the moment the heap ran out, and only a flag set in advance gets it:

java -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dumps -XX:+ExitOnOutOfMemoryError -jar app.jar

What HeapDumpPath actually does depends on what it points at. Each row was produced by a small program that leaks 1 MiB arrays into a 64 MiB heap:

HeapDumpPath valueResult on JDK 17
unsetjava_pid<pid>.hprof in the working directory
an existing directory<dir>/java_pid<pid>.hprof, a new file per process
a file namethat file; the next process that dies finds it and logs Unable to create ...: File exists, so the second incident has no dump
app-%p.hprofwritten literally as app-%p.hprof
missing/ (no such directory)Unable to create missing/: No such file or directory, no dump
missing (no slash, no such path)a file called missing

So point it at a directory that exists. The %p row contradicts the Oracle java manual, which gives -XX:HeapDumpPath=./java_pid%p.hprof as an example; the 17 heapDumper.cpp source has no pid substitution and the run wrote the name unchanged. The OpenJDK source gains %p expansion in JDK 25.

The related flags, all verified with java -XX:+PrintFlagsFinal -version:

  • HeapDumpGzipLevel (default 0, present in 17): -XX:HeapDumpGzipLevel=1 compresses, and the directory form names the file java_pid<pid>.hprof.gz.
  • One dump per JVM. A program that caught three OutOfMemoryErrors got one dump. OnOutOfMemoryError="cmd %p" also ran once, after the dump, with %p replaced by the pid.
  • ExitOnOutOfMemoryError dumps first, then prints Terminating due to java.lang.OutOfMemoryError: Java heap space and exits with status 3, which is what lets an orchestrator restart a sick JVM instead of leaving it limping. CrashOnOutOfMemoryError instead aborts with an hs_err_pid<pid>.log crash report.
  • HeapDumpBeforeFullGC and HeapDumpAfterFullGC dump on every full GC, numbered java_pid<pid>.hprof, .hprof.1, .hprof.2: three System.gc() calls with both flags wrote six files. Use them for minutes, not as a standing setting.

These flags are manageable, so a JVM started without them can be fixed without a restart:

jcmd 48076 VM.set_flag HeapDumpOnOutOfMemoryError true
jcmd 48076 VM.set_flag HeapDumpPath /dumps

The worked case: a demo order service whose cache never evicts, started with -Xmx128m, the flags above and -XX:HeapDumpPath=dumps, died 30 seconds in with Dumping heap to dumps/java_pid55039.hprof ..., Heap dump file created [138598231 bytes in 0.079 secs], then exit status 3. Its GC log shows the same death from the other side, 28 full GCs in the last 2.3 seconds, which the GC logging guide uses as its example.

From inside the application

HotSpotDiagnosticMXBean.dumpHeap(file, live) is the same dump from Java code, for an admin endpoint or a test harness:

HotSpotDiagnosticMXBean hs = ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);
hs.dumpHeap("/dumps/app.hprof", true); // true = live objects only, after a full GC

The javadoc's rules held exactly: a relative name resolves against the JVM's working directory, a name without .hprof throws IllegalArgumentException: heapdump file must have .hprof extention (the JDK's spelling), and an existing file throws IOException: File exists. In jconsole the same bean is com.sun.management:type=HotSpotDiagnostic under the MBeans tab, operation dumpHeap; JDK Mission Control reaches it through its MBean browser, and VisualVM has a Heap Dump action on the application's right-click menu. On servers these GUIs need a JMX connection, so they are rarely the fast path.

Spring Boot Actuator serves a dump at /actuator/heapdump. The endpoint's source in the Spring Boot repository declares defaultAccess = Access.NONE, matching the reference docs' statement that every endpoint except shutdown and heapdump is unrestricted by default, so it takes both management.endpoint.heapdump.access=unrestricted and adding heapdump to management.endpoints.web.exposure.include. The same source writes the dump to a temporary .hprof file in the JVM's temp directory before streaming it, honours ?live=false, answers a concurrent request with 429, and defaults to live objects. On a public port it publishes every secret in memory: keep it behind a management port and authentication, or off.

Docker and Kubernetes

The commands do not change; where the file lands does. With no shell access to the node, run jcmd inside the container, onto a volume:

kubectl exec -n shop orders-7d9f -c app -- jcmd 1 GC.heap_dump /dumps/heap.hprof
kubectl cp shop/orders-7d9f:/dumps/heap.hprof ./heap.hprof -c app

The image needs a full JDK for jcmd (a JRE-only image has none), and the kubectl cp reference states that it requires tar in the container image and suggests kubectl exec for cases tar cannot handle. For the automatic dump, set the flags through JAVA_TOOL_OPTIONS, which the JVM picks up and announces as Picked up JAVA_TOOL_OPTIONS, and point HeapDumpPath at a mounted volume. Three container-specific ways to lose the dump:

  • The writable layer. A dump written to the container's own filesystem is gone when the kubelet restarts it; the Kubernetes volume docs say data on a pod's volumes survives container restarts.
  • A memory-backed emptyDir. With medium: Memory, the Kubernetes docs warn that files written "count against the memory limit of the container that wrote them": a 2.5 GB dump into tmpfs can push the container over its limit mid-write.
  • The pause versus the probes. The dump freezes the JVM for seconds (next section) and the liveness probe's timeoutSeconds defaults to 1 second; enough failed probes and the kubelet kills the container, truncating the file. Relax the probe before a manual dump on a large heap.

A kernel OOM kill (the pod status OOMKilled) is not a Java OutOfMemoryError. The Kubernetes memory docs say a container that keeps using memory beyond its limit is terminated, and no Java exception is thrown first, so HeapDumpOnOutOfMemoryError never fires. If the pod dies that way, the container limit is too tight for heap plus native memory; size -Xmx below the limit and dump by hand while memory climbs.

What a dump costs: pause, size and disk

Measured on a 10-core laptop, G1, -Xmx4g, about 2,286 MiB of live session objects (strings, maps and pseudo-random byte payloads), timings from -Xlog:safepoint:

CommandApplication frozenFile size
jcmd <pid> GC.heap_dump4.79 s (the full GC inside it took 1.15 s)2,690,498,695 bytes
jcmd <pid> GC.heap_dump -all3.69 s2,691,612,871 bytes
jcmd <pid> GC.heap_dump -gz=17.99 s1,402,990,414 bytes (52%)
jcmd <pid> GC.heap_dump -gz=622.42 s1,345,241,570 bytes (50%)
jcmd <pid> Thread.print, for scale0.75 ms
Bar chart of application pause per heap dump command on a 2.3 GB heap: 4.79 s plain, 3.69 s with -all, 7.99 s with -gz=1 and 22.42 s with -gz=6, with file sizes of 2.69, 2.69, 1.40 and 1.35 GB
Bar chart of application pause per heap dump command on a 2.3 GB heap: 4.79 s plain, 3.69 s with -all, 7.99 s with -gz=1 and 22.42 s with -gz=6, with file sizes of 2.69, 2.69, 1.40 and 1.35 GB

The whole dump is stop-the-world: compression happened inside the pause, so -gz trades disk for downtime, and level 6 bought 2 points of size for 14 extra seconds. live is not free either: its full GC is part of the pause, and on a heap full of garbage it saves far more file than it costs. And size is content-dependent: the same service's mostly zero-filled cache compressed about 14 times at -gz=1, against 1.9 times here.

The file can exceed the heap. The 2,286 MiB live set wrote 2,566 MiB, and the -Xmx128m crash wrote 132.2 MiB, more than the heap's maximum. The dump header declares 8-byte identifiers, so every reference that a 64-bit JVM with compressed references holds in 4 bytes takes 8 in the file, and each object record adds its own tag, id, class id and length. Budget disk for the maximum heap plus a margin on the volume behind HeapDumpPath.

A heap dump is a copy of your secrets

Everything the heap held is in the file as bytes. A 40 MB version of the session cache above, dumped and searched with nothing cleverer than grep -a, gave up all 5,000 distinct user email addresses and 15,841 UUID-shaped tokens. Compact strings in JDK 9 and later store Latin-1 text one byte per character, so plain search finds them.

Handle the file like a database export: keep the 0600 permissions when copying, move it over an encrypted channel, delete it from the node afterwards, never attach it to a ticket, and analyse it locally. The Java Heap Dump Analyzer parses in the browser tab and sends nothing, which is the design point.

JDK 8 differences

On JDK 8 the same jcmd command exists but its source offers only -all: no -gz, no -overwrite, and no HeapDumpGzipLevel flag. jmap -dump:live,format=b,file=heap.hprof <pid> is the common JDK 8 form, and its manual documents -F to force a dump from a JVM that does not respond, without live. JDK 17 rejects -F and points to jhsdb jmap instead. HeapDumpOnOutOfMemoryError, HeapDumpPath (file or directory) and ExitOnOutOfMemoryError are in the JDK 8u flag table.

Which method for which situation

SituationUse
Memory is climbing now, you have a shelljcmd <pid> GC.heap_dump /dumps/heap.hprof
Leak suspected, heap mostly garbage, disk tightthe same, live is the default
Process cannot afford a full GC, or garbage is the questionjcmd <pid> GC.heap_dump -all ...
Slow network or small disk, pause acceptable-gz=1, never higher
The crash happens at 3 a.m.-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=<dir> plus ExitOnOutOfMemoryError
JVM already running without that flagjcmd <pid> VM.set_flag HeapDumpOnOutOfMemoryError true
Dump from application code or a testHotSpotDiagnosticMXBean.dumpHeap
Kubernetes podkubectl exec ... jcmd 1 GC.heap_dump to a volume, then kubectl cp
JDK 8 JVM that does not respondjmap -F -dump:format=b,file=...

If memory is not the complaint and the process is stuck instead, a Java thread dump costs a thousandth of the pause and should come first.

Tools for this job

  • Java Heap Dump Analyzer: drop the .hprof (decompress a -gz dump first); class histogram, biggest objects and duplicate arrays, streamed locally at any size.
  • Java GC Log Analyzer: a climbing heap floor in the GC log is the evidence that a dump is worth its pause.
  • Java Thread Dump Analyzer: for the stuck process, before or instead of a heap dump.

For reading what you captured, the heap and thread dump analysis guide covers histograms and leak signatures, and the GC log and HAR reading guide covers the GC side.

Frequently asked questions

Does taking a heap dump stop the application?

Yes, for the whole write. Every Java thread waits at a safepoint while the VM walks the heap, and the default live dump adds a full GC inside that pause. On a 2.3 GB live heap the plain dump froze the JVM for 4.79 seconds, and gzip level 1 stretched it to 7.99 seconds.

Why is there no heap dump after my pod was OOMKilled?

Because the kernel killed the process, and no Java OutOfMemoryError was ever thrown. HeapDumpOnOutOfMemoryError only fires on the Java exception. An OOMKilled status means heap plus native memory crossed the container limit, so lower -Xmx below the limit and capture a manual dump while memory climbs.

Can I open a gzipped heap dump directly?

Not in most analyzers, which read plain HPROF. Run gunzip heap.hprof.gz first and allow disk for the full size again. The -gz option exists to make the copy off the server cheaper, at the price of a longer pause while the JVM compresses.

Should I use live or all?

Use live, the jcmd default, for leak hunting: the full GC removes garbage so the histogram shows what is actually retained. Use all when the process should not take a full GC, or when the question is what was allocated, such as a churn problem. Remember jmap defaults to all.

Sources and further reading

Browse all tools