Heap dump is snapshot of java memory. This Java memory is mainly used by the application. The heap (in a JVM) is the place where a JVM keeps all its runtime objects. The JVM creates a dedicated space for the heap at the JVM startup, which can be controlled via the JVM option -Xms<size> eg: -Xms100m (this will allocate 100MBs for the heap). The JVM is capable of increasing and decreasing the size of the heap based on the demand, and the JVM has another option which allows to set a max size for the heap: -Xmx<size>, eg: -Xmx6g (this allows the heap to grow up to 6GBs).
The JVM automatically performs Garbage Collection (GC) when it detects that the JVM is about to reach the max heap size. But the GC can only clean the objects which are eligible for GC. If the JVM can’t allocate required memory even after GC, JVM will crash with “Exception in thread “main” java.lang.OutOfMemoryError: Java heap space”.
If your Java application in production crashes due to some issue like this, you can’t just ignore the incident and restart your application. You have to analyze the what caused the JVM to crash, and take the necessary actions to avoid it happening again. This is where the JVM heap dump comes into play.
If JVM heap dumps are by default disabled, you have to enable heap dumps explicitly by providing the following JVM option: -XX:+HeapDumpOnOutOfMemoryError.
Creating a heap dump of a running application cause the application to halt everything for a while. So, it is not recommended to use in production system.
Sometimes we might require Heap Dump in an on-demand basis. For example, during the peak load, an application may become slower and the memory consumption might be more. To troubleshoot the memory consumption, we require Heap Dump. We have to pass the below JVM arguments to get the Heap Dump when the application throws an “OutOfMemoryError“.
Command >> jmap -dump:format=b,file=<file_name> <pid>
For example, jmap -dump:format=b,file=heap_dump.hprof 4234
In the above example, the 4234 is the Java process id There is another GUI utility called jconsole. jconsole can connect to local Java process or remote Java process. By using MBeans we can get the heap dump.
All the above said tools are part of JDK. Set the JAVA_HOME and PATH environment variables to access the tools.
In the next article, we will look into garabage collector. Until then, STAY TUNED!!!
Happy Learning !!!
If you have doubt or queries, you can definetely comment us or can mail us on [email protected]
Related Searches :