So your application is running out of memory, you’re spending days and nights analyzing your application hoping to catch the memory holes in your objects. This article will explain how to monitor and detect your memory leaks to make sure your app is on the safe side.
Memory Leak Suspicion
If you suspect that there is a memory leak, a convenient way to make sure it’s really there is using JConsole. You can locally or remotely connect JConsole to your app and let it monitor for a while (an hour, half a day, overnight, or even a week).
After connecting JConsole to your app, start analyzing the “memory” tab.
A memory leak would look like this:
How to Find the Leaking Sources in Your Application
For this purpose, I recommend using JVisualVM. This tool is part of the JDK. Inside JVisualVM you can make a heap dump file (Inside the “monitor” tab). Please keep in mind that it’s not possible to create a heap dump remotely.
You’ll need to either run JVisualVM on the same machine or execute a JMap command to produce a heap dump file and import it later into JVisualVM. (JMap is an Oracle tool that prints a memory map tree for all objects for a given process. Here’s the documentation for JMap.)
So, basically, you run the JMap on your remote server (your production environment, for instance) and then analyze that file locally.
I recommend doing several heap dumps. That will give you a better picture of whether you have memory leaks.
Analyzing the Heap Dump File
I personally like to use MAT (Memory Analyzer). MAT takes the heap dump file and helps you find memory leaks. MAT shows you exactly which instances have memory growth suspects. You might notice a Java library instance as a "problem suspect," such as “java.lang.Class”, but this is normal.
An example of a leak detection:
Here you can see the exact instance that is suspected to be a leaking component.
Analyze Suspected Objects
The next step is to go to the details field of the suspected instance and investigate the objects inside:
In the above example you can clearly see that the TreeMap field is growing.
Fix Your Leak and Run the Test Again
Now what’s left is to understand and fix your leaking code – but of course this is different for each object.
I hope these directions will help you detect leaking memory objects.