How to Generate JVM Heap Memory Dump?
Last Updated :
23 Aug, 2021
Java Heap dump is a snapshot of all java objects that are present in the JVM(Java Virtual Machine) at a certain point in time. The JVM allocates memory for objects which are class instances or arrays in the heap memory. When the objects are no longer needed or are no more referenced, the Garbage Collector runs and reclaims the memory space occupied by these objects.
The heap dump is in binary format, and it has .hprof extension. It can be opened and analyzed using applications like JVisualVM and Eclipse MAT(Memory Analyzer Tool). We generate java memory heap dump to identify issues like memory leaks and to optimize memory usage in our application.
Methods:
There are different ways of generating a java memory heap dump. JDK comes up with various tools for generating heap dump. These tools are located in bin folder under JDK home directory.. Let us discuss how to generate JVM Heap Dump which is as follows:
- Using jmap command
- Using jcmd command on terminal
- Using the JVisualVM tool
- Identifying HeapDumpOnOutOfMemory
- Using JMX Console
- Using HotSpotDiagnosticMBean by writing a program
Method 1: Using map command
jmap is a command which you run inside the bin folder of your JDK home directory. It gives statistics about memory usage. The structure is as follows:
Example
jmap -dump:[live],format=b,file=<file-path> <pid>
live:- This parameter is optional. If set, it prints all those objects that
have active references.
format = b , which means the heap dump file is in binary format. It is not necessary
to set this parameter.
file =<file-path> indicates where the heap dump file will be generated.
<pid> :- process id of the java process

Now in order to get the process id of a running java process, one can use one of the below options as defined:
1.1
jps
We type this command from a Unix terminal or Windows Command prompt where JDK is installed. It gives the process ID of the running java process

jps command
1.2
ps -eaf| grep java
This gives the process ID of all running java processes. It works only on a Unix Terminal

ps -eaf | grep java
1.3 Using task manager application in windows operating systems.
Method 2: Using jcmd command on terminal
This command sends a request to the JVM to generate a heap dump. One of its parameters is GC.heap_dump. It is as shown below:
jcmd <pid> GC.heap_dump <file-path>
<pid> - Process id of java process
<file-path> - Path where the heap dump is to be generated

jcmd
Method 3: Using the JVisualVM tool
This is a tool that is packaged within JDK. It helps to monitor and troubleshoot java applications. It has a Graphical User Interface that is simple and intuitive. We type jvisualvm in the start menu, or we go to the bin directory of JDK home directory through command prompt or terminal window in Unix and type jvisualvm
It launches a Java Visual VM application. On the left side, it shows the currently running java process. Right-click the process ID whose heap dump you wish to generate. When we click on heap dump, it generates heap dump for the selected process. Under Basic info, it shows the file path where the heap dump is generated.

Method 4: Identifying HeapDumpOnOutOfMemory
It is ideal to capture heap dumps when an application experiences java.lang.OutOfMemoryError. Heap dumps help identify live objects sitting in the memory and the percentage of memory it occupies.
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=<file-path>
While running your java application when this system property is set, JVM takes a snapshot of the heap dump when it encounters OutOfMemoryError.
Method 5: Using JMX Console
There is a Hotspot Diagnostic MBean which has a heap dump operation. We use jmx clients like jconsole to invoke the MBean operation. Through JConsole, we can either connect to a local java process or a remote process by specifying the host and port number and username/password. Once we connect to the process id, jconsole applications open with multiple tabs. The Overview tab shows Heap Memory usage, threads, classes, CPU usage

Jconsole – new connection

Jconsole – MBeans tab
Method 6: Using HotSpotDiagnosticMBean by writing a program
We use HotSpotDiagnosticMBean to invoke the heap dump operation. We get the MBean object from the MBean platform server. In the below example, we have used reflection to invoke the heapDump() method of the MBean object.
Example
Java
import java.io.*;
class GFG {
private static final String HOTSPOT_BEAN
= "com.sun.management:type=HotSpotDiagnostic" ;
private static volatile Object hotSpotMBean;
static void generateHeapDump(String fileName,
boolean live)
{
initHotspotMBean();
try {
Class clazz = Class.forName(
"com.sun.management.HotSpotDiagnosticMXBean" );
Method m = clazz.getMethod(
"dumpHeap" , String. class , boolean . class );
m.invoke(hotSpotMBean, fileName, live);
}
catch (RuntimeException re) {
throw re;
}
catch (Exception exp) {
throw new RuntimeException(exp);
}
}
private static void initHotspotMBean()
{
if (hotSpotMBean == null ) {
synchronized (JavaHeapDump. class )
{
if (hotSpotMBean == null ) {
hotSpotMBean = getHotSpotMbean();
}
}
}
}
private static Object getHotSpotMbean()
{
Object hotspotBean = null ;
try {
Class clazz = Class.forName(
"com.sun.management.HotSpotDiagnosticMXBean" );
MBeanServer mbeanServer
= ManagementFactory
.getPlatformMBeanServer();
hotspotBean
= ManagementFactory.newPlatformMXBeanProxy(
mbeanServer, HOTSPOT_BEAN, clazz);
return hotspotBean;
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return hotspotBean;
}
public static void main(String[] args)
{
String fileName
= "/home/suchitra/Desktop/suchitra/projects/java-concurrency-examples/JavaHeapDumpGenerator/src/heap1.hprof" ;
boolean live = true ;
switch (args.length) {
case 2 :
live = args[ 1 ].equals( "true" );
case 1 :
fileName = args[ 0 ];
}
generateHeapDump(fileName, live);
}
}
|
Note:
We run this application by passing command-line arguments for file path where the heap dump is to be generated and live parameter which can be set as true or false. When this java code is run, it generates a heap1.hprof file in src folder. This heap dump can be analyzed using MAT(Memory Analyzer Tool). This can be installed as a plugin in Eclipse from Marketplace.

Heap Dump Analysis using MAT
- Now lastly let us analyze the heap dump file with help of JVisualVM.
- Once a heap dump file is generated, we use tools like JVisualVM to analyze the file. When you open a heap dump, Java VisualVM displays the Summary view by default. The Summary view displays the running environment where the heap dump was taken and other system properties.
- In JvisualVM, we go to File -> Load and select the folder location where the ‘.hprof file’ is generated which is pictorially aided below to get a fair understanding for the same.

Analysis of heap dump file – Summary tab

Analysis of heap dump – Classes tab
Similar Reads
Heap and Stack Memory Errors in Java
Memory allocation in java is managed by Java virtual machine in Java. It divides the memory into stack and heap memory which is as shown below in the below media as follows: Stack memory in Java It is the temporary memory allocation where local variables, reference variables are allocated memory whe
5 min read
How to Use Memory Heap Dumps Data in Android?
When we design an Android application, the most prevalent concern among developers is the program's memory utilization. This is because, the majority of people use low-memory devices, if your program uses a lot of memory, you can lose users. The developers are attempting to locate each and every mem
6 min read
How is the default max Java Heap size determined?
In the Client JVM: The default maximum heap size is half of the physical memory up to a physical memory size of 192 megabytes and otherwise one-fourth of the physical memory up to a physical memory size of 1 gigabyte. Example: If a machine has 128 megabytes of physical memory, then the maximum heap
2 min read
What is a Memory Heap?
What is Heap memory? Heaps are memory areas allocated to each program. Memory allocated to heaps can be dynamically allocated, unlike memory allocated to stacks. As a result, the heap segment can be requested and released whenever the program needs it. This memory is also global, which means that it
5 min read
How Many Types of Memory Areas are Allocated by JVM?
JVM (Java Virtual Machine) is an abstract machine, In other words, it is a program/software which takes Java bytecode and converts the byte code (line by line) into machine-understandable code. JVM acts as a run-time engine to run Java applications. JVM is the one that calls the main method present
4 min read
IntStream generate() method in Java
IntStream generate(IntSupplier s) returns an infinite sequential unordered stream where each element is generated by the provided IntSupplier(a supplier of int-valued results). This is suitable for generating constant streams, streams of random elements, etc. Syntax : static IntStream generate(IntSu
1 min read
Java Stack vs Heap Memory Allocation
In Java, memory allocation is primarily divided into two categories i.e. Stack and Heap memory. Both are used for different purposes and they have different characteristics. Stack Memory: This memory is used to store local variables, method calls, and reference data during program execution.Heap Mem
4 min read
How to Convert HashMap to ArrayList in Java?
In Java a HashMap is a collection that stores key-value pairs on the other hand, an ArrayList is a collection that stores dynamic arrays. There are some scenarios where we need to convert a HashMap into an ArrayList such as: Extracting only the keys or values in the list form.Converting key-value pa
3 min read
How are Java Objects Stored in Memory?
In Java, all objects are dynamically stored in the Heap memory while references to those objects are stored in the stack. Objects are created with the help of "new" keyword and are allocated in the heap memory. However, declaring a variable of a class type does not create an object it only creates r
5 min read
How to find max memory, free memory and total memory in Java?
Although Java provides automatic garbage collection, sometimes you will want to know how large the object heap is and how much of it is left. This information can be used to check the efficiency of code and to check approximately how many more objects of a certain type can be instantiated. To obtain
3 min read