Wednesday 31 December 2014

How to detect and fix Memory Leak – OutOfMemoryError

How to detect and fix Memory Leak – OutOfMemoryError – Heap Space

Step 1: To detect and fix a memory leak in Java, we will be using JVisualVM which is free open source tool that comes bundled with JDK. To open this application, refer to the path in following snapshot:



Step 2 : Let us create a java program that can be the cause of Memory leakage. In this program we will create a POJO class and instantiate it infinite times in a loop and keep adding it into an Arraylist.
After running for few seconds, the program will throw the famous OutOfMemoryError: Java Heap Space.



Step 3: JVisualVM will reflect the status of Heap. To view this click on the respective java program in Applications side bar of JVisualVM.
Refer to the following snapshot:





Step 4: Now that you have seen the error it is time to detect the root cause of the same. For this enable the ‘Heap Dump on OOME’ property of your java program in JVisualVM. For this right click your program and click on ‘Enable Heap Dump on OOME’.

Refer to the following snapshot:




Enabling this will ensure that Heap dumps will be generated at time of OutOfMemoryError in your program.
The heap dumps are usually used to analyze the root cause of any memory related error. It is basically a snapshot of JVM internals like total classes loaded during a program execution, total instances created, which class had how many instances etc.



Step 5: Re-run your java program to replicate the problem and this time we will use generated heap dump to analyze the cause of error.





Step 6: To open the Heap dump, go to JVisualVM, click File -> Load. Browse to the path of Heap dump location.

For example, in our case the dumps were created at location:

C:\Users\User1\AppData\Local\Temp\visualvm.dat\localhost_688\heapdump-1420002430567.hprof

Refer to snapshot below for the same:





Step 7: The Summary tab of heap dump will display the basic information like number of classes loaded, total instances created, the environment in which program was executed etc.

Refer to the snapshot below:



Step 8: To detect the root cause of error, click on Classes tab. This displays the number of instances created for each loaded class.
As in our case, the OOM error was there due to high number of instances of class MyPOJO.

Refer to the snapshot below for the same:



There was huge number of instances around 13,845,151 for class MyPOJO.

Step 9: Now that we have discovered the root cause of the problem, next step will be to resolve the same. In our case we can modify the program to not run an infinite loop, so that we can control the number of instance creation.
Similarly, you can too dry run your code to find out the resolution of known root cause.