How to Capture Java Heap Dumps Efficiently with jmap, jcmd, and JVisualVM
This guide explains multiple ways to capture Java heap dumps—including jmap, JVM flags, jcmd, JVisualVM, JMX, and programmatic methods—detailing command syntax, best‑practice options, and step‑by‑step procedures for effective memory‑issue diagnosis.
Heap dumps are essential for diagnosing memory leaks, garbage‑collection problems, java.lang.OutOfMemoryError, and for optimizing memory consumption.
jmap
jmap is bundled with the JDK and can write a heap dump to a specified file.
jmap -dump:format=b,file=<file-path> <pid>
# pid: Java process ID
# file-path: destination file for the dumpExample:
jmap -dump:format=b,file=/opt/tmp/heapdump.bin 37320Use the live option to include only live objects and keep the dump size manageable.
HeapDumpOnOutOfMemoryError
Setting the JVM flag -XX:+HeapDumpOnOutOfMemoryError makes the JVM automatically generate a heap dump when an OOM occurs.
Specify the output location with -XX:HeapDumpPath.
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/opt/tmp/heapdump.binBest practice: enable this flag in all applications to ensure a dump is captured at the moment of failure.
jcmd
jcmd, also part of the JDK, sends diagnostic commands to a running JVM.
jcmd <pid> GC.heap_dump <file-path>
# pid: Java process ID
# file-path: destination file for the dumpExample:
jcmd 37320 GC.heap_dump /opt/tmp/heapdump.binJVisualVM
JVisualVM is a graphical monitoring and troubleshooting tool bundled with the JDK.
Launch jvisualvm from the JDK bin directory.
Right‑click a Java process and choose “Heap Dump”.
The dump is written to the file path shown under the “Summary → Basic Info → File” tab.
JMX (HotSpotDiagnostic MBean)
The MBean com.sun.management:type=HotSpotDiagnostic provides a dumpHeap operation. outputFile: path for the heap dump. live: set to true to capture only live objects.
Clients such as JConsole, jmxsh, or Java Mission Control can invoke this operation. Example using JConsole is shown below.
Programmatic Capture
Applications can trigger a heap dump programmatically by calling the same HotSpotDiagnostic MBean via JMX.
// Example Java code to invoke dumpHeap
HotSpotDiagnosticMXBean mxBean = ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);
mxBean.dumpHeap("/opt/tmp/heapdump.bin", true); // true = live objects onlySigned-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
