Question - What is the purpose of heap dumps and how do you analyze a heap dump?
Answer -
Heap dumps consist of a snapshot of all live objects on Java heap memory that are used by running Java applications. Detailed information for each object like type, class name, address, size and references to other objects can be obtained in the heap dump. Various tools help in analyzing heap dumps in Java. For instance, JDK itself provides jhat tool for analysing heap dump. Heap dumps are also used for analysing memory leaks which is a phenomenon that occurs when there are objects that are not used by the application anymore and the garbage collection is not able to free that memory as they are still shown as referenced objects. Following are the causes that result in memory leaks:
- Continuously instantiating objects without releasing them.
- Unclosed connection objects (such as connections to the database) post the required operation.
- Static variables holding on to references of objects.
- Adding objects in HashMap without overriding hashCode() equals() method. If these methods are not included, then the hashmap will continuously grow without ignoring the duplicates.
- Unbounded caches.
- Listener methods that are uninvoked.
Due to this, the application keeps consuming more and more memory and eventually this leads to OutOfMemory Errors and can ultimately crash the application. We can make use of the Eclipse Memory Analyzer or jvisualVM tool for analysing heap dump to identify memory leaks.