Scrivio Interview library
ConceptFoundations7 min read · updated 12 November 2026

How do you capture a heap dump automatically on OutOfMemoryError and manually from a running process? What risks should you consider?

Automatically, we start the JVM with -XX:+HeapDumpOnOutOfMemoryError and -XX:HeapDumpPath, so it writes a dump the first time an OutOfMemoryError is thrown. Manually, jcmd <pid> GC.heap_dump <file> writes one on demand; by default it dumps only live objects, which forces a full GC first. The risks are the pause, which grows with the heap size, the file size, about as large as the used heap, which needs disk space that in Kubernetes must survive the pod restart, and the content: a heap dump holds every piece of data in memory, including personal data and secrets, so it must be treated as sensitive.

Why this question is asked

A heap dump is the single most useful artifact for a memory problem: a complete picture of every object in the heap and who refers to it. It is also heavy, slow to take and full of data we are not allowed to spread around. Interviewers ask this question to see whether we can collect one reliably at the moment it matters and whether we think about the side effects. In this answer, we will recap what a heap dump is, configure automatic dumps on OOM, take a manual dump with jcmd, and then go through the pause, the disk and storage questions, and the data sensitivity.

1A Quick Recap: What a Heap Dump Contains

A heap dump is a file, usually in the HPROF format, that records every object on the Java heap at one moment: its class, its field values, and the references between objects, plus the GC roots, such as thread stacks and static fields, that keep objects alive. Analysis tools like Eclipse MAT or VisualVM read it and answer questions such as which objects take most memory and why they are still reachable.

Because it includes field values, a heap dump contains the actual data: strings, byte arrays, request bodies, cached customer records, session tokens and any secret that was in memory at that moment.

2Capturing a Dump Automatically on OutOfMemoryError

The most important dump is the one taken at the moment of failure, when the heap is full of whatever caused it. We cannot rely on a person being there, so we configure the JVM to do it.

Shell
java -XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=/diagnostics \
-XX:+ExitOnOutOfMemoryError \
-jar orders.jar
# on the first OutOfMemoryError:
# java.lang.OutOfMemoryError: Java heap space
# Dumping heap to /diagnostics/java_pid1.hprof ...
# Heap dump file created [1843210456 bytes in 9.812 secs]
# Terminating due to java.lang.OutOfMemoryError: Java heap space

When HeapDumpPath is a directory, the JVM names the file java_pid<pid>.hprof. It writes a dump only for the first OutOfMemoryError in the process's life, and it does not overwrite an existing file with the same name, which matters when the container restarts with the same pid 1 and the volume keeps the old file; using a per-pod subdirectory or cleaning up after collection avoids losing the second dump. Combining it with ExitOnOutOfMemoryError means the dump is written first and then the JVM exits, so the orchestrator can restart it cleanly.

3Capturing a Dump Manually With jcmd

For a leak that grows slowly, we do not want to wait for the crash. We take a dump while the service is running.

Shell
jcmd 4711 GC.heap_dump /diagnostics/orders-live.hprof
# 4711:
# Dumping heap to /diagnostics/orders-live.hprof ...
# Heap dump file created [702381442 bytes in 3.114 secs]
jcmd 4711 GC.heap_dump -all /diagnostics/orders-all.hprof # include unreachable objects too
jcmd 4711 GC.heap_dump -gz=1 /diagnostics/orders.hprof.gz # compressed (recent JDKs; check your version)
Two ways to get a heap dump
On OutOfMemoryErrorjcmd GC.heap_dump
Triggerfirst OOM in the processon demand
Setupflags at JVM startnone; attach to running JVM
Objectsheap as it is at the failurelive only by default (full GC first)
Typical usecrash evidenceslow leaks, before the crash
Main risklost if written to an ephemeral diskpause on a serving instance

By default, GC.heap_dump dumps only live objects, those still reachable. To find them, it runs a full GC first, which adds to the pause but makes the file smaller and the analysis cleaner. The -all option skips that GC and includes garbage, which is occasionally useful but usually not. The file path is opened by the target JVM, so it is relative to the target's working directory and must be writable by the target's user. The older jmap -dump:live,format=b,file=... does the same job.

4Risk 1: The Pause

Writing a heap dump is a stop-the-world operation: the JVM halts all application threads at a safepoint while it walks the heap and writes the file, and with the live option it first runs a full GC. The pause grows with heap size and disk speed. A 2 GB heap may pause for a few seconds; a 30 GB heap can pause for a minute or more. During that time the instance answers nothing, health checks may fail and the orchestrator may kill it mid-dump.

So on a serving instance we first take it out of traffic, for example by failing the readiness probe or draining it from the load balancer, and make sure the liveness probe will not restart it during the dump. Recent JDKs can write dumps with several threads, which shortens the pause; check your version.

5Risk 2: Disk Space and Surviving the Restart

The file is roughly as large as the used heap, a bit less with only live objects, and compression helps at the cost of more CPU and time. A 6 GB heap needs about 6 GB of free space, and if the dump fills the disk, a container's writable layer or a shared node disk, it can break the service or get the pod evicted.

In Kubernetes the dump must also survive the pod. After an OOM with ExitOnOutOfMemoryError, the container restarts, and anything written to its own file system is gone. So HeapDumpPath points at a mounted volume that outlives the container: a persistent volume, or an emptyDir, which survives container restarts within the same pod but not the pod's deletion. A small sidecar or job that uploads new dumps to secure storage and deletes them locally completes the setup.

6Risk 3: The Data Inside

A heap dump is effectively a copy of everything the service was handling: personal data from requests and caches, database rows, access tokens, API keys and passwords held in strings or byte arrays. It must be handled like a production database extract. That means storing it in encrypted, access-controlled storage, keeping it only as long as the analysis needs, analysing it in a controlled environment rather than on a personal laptop, and logging who downloaded it. Sharing a dump with a vendor or attaching it to a public issue tracker is a data leak, and that rule belongs in the runbook so it is followed under pressure.

7Follow-up questions

Why did my OOM not produce a dump?

Common reasons are a missing or unwritable HeapDumpPath, a full disk, an existing file with the same name, or an OOM that is not a Java heap OOM. If the kernel killed the process because the container exceeded its memory limit, there was no Java OutOfMemoryError at all, so no dump is written.

Is a class histogram a safer alternative?

Often yes. jcmd <pid> GC.class_histogram shows instance counts and bytes per class, takes much less time, produces a tiny file, and contains no field values. It is a good first step; the heap dump is needed when we must see who holds the objects.

Does HeapDumpOnOutOfMemoryError slow down normal operation?

No. It only acts when an OutOfMemoryError happens, so there is no cost until then. The cost is the pause and the disk space at the moment of the failure.

8Conclusion

In this answer, we captured heap dumps automatically with HeapDumpOnOutOfMemoryError and HeapDumpPath, which write a dump on the first OOM, and manually with jcmd GC.heap_dump, which dumps live objects after a full GC by default. We then went through the risks: a stop-the-world pause that grows with the heap, a file as large as the used heap that needs space and, in Kubernetes, a volume that survives the restart, and contents that include personal data and secrets and must be handled as sensitive.

What to say in the interviewAbout 90 seconds aloud

Open with

For the automatic case, I start the JVM with HeapDumpOnOutOfMemoryError and HeapDumpPath pointing at a directory, and in containers usually also ExitOnOutOfMemoryError, so the dump is written first and then the JVM exits and gets restarted.

Then, if they want more

It only dumps on the first OOM, names the file java_pid with the pid, and won't overwrite an existing file, so I use a per-pod directory. For the manual case, jcmd pid GC.heap_dump with a file path.

By default that dumps only live objects, so it runs a full GC first; minus all includes garbage, and recent JDKs can compress it. The path is opened by the target JVM, so it's in the target's file system and must be writable by its user. Then the risks.

First the pause: dumping is stop the world and grows with the heap, seconds for a couple of gigabytes, a minute or more for tens, so I take the instance out of traffic and make sure the liveness probe won't kill it mid-dump.

Second, disk: the file is about the size of the used heap, so I need the space, and in Kubernetes it has to go to a volume that survives the container restart, otherwise the evidence disappears.

Third, content: a heap dump contains everything in memory, personal data, tokens, passwords, so I handle it like a production data extract, encrypted storage, restricted access, short retention, never on a laptop.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How do you capture a heap dump automatically on OutOfMemoryError and manually from a...": https://scrivio-interview-library.netlify.app/java/jvm-diagnostics/e44dafd4f3/