Java Heap Dump

Memory leaks are notoriously hard to debug. Java, with its built in garbage collector, handles most memory leak issues. True memory leak happens when objects are stored in memory but are not accessible by running code. These kinds of inaccessible objects are handled by Java garbage collector (in most cases). Another type of memory leak happens when we have an unneeded reference to the object somewhere. These are not true memory leaks as objects are still accessible, but none the less can cause some nasty bugs.

For example, storing large objects in session and not cleaning its references. This kind of issue will often go unnoticed until we get a large number of concurrent users and your application starts throwing out of memory errors. Without load test this will most probably happen in production.
One way to find memory leaks is analyzing heap dumps. There are several ways to get a heap dump (not including 3rd party tools):

1. HeapDumpOnCtrlBreak
Add this option when starting JVM. It will create heap dump every time ctrl+break (kill -3) signal is sent to JVM. HeapDumpPath is used to set location of heap dumps.

2. HeapDumpOnOutOfMemoryError
This JVM option will create heap dump every time when your application throws an OutOfMemoryError. HeapDumpPath is used to set location of heap dumps.

3. Jmap
Jmap is a tool that comes with JDK installation. To use it we need a PID of our java process.
Then we can use it like this:

jmap -dump:file=D:\temp\heapdumps\dump.bin 1234

4. Jmap (from the application)
We can also use jmap from our code. To get a pid from code use we need to use

String name = ManagementFactory.getRuntimeMXBean().getName();
String pid = name.substring(0, name.indexOf("@"));
After that we can start jmap process like this:
String[] cmd = { "jmap", "-dump:file=D:\\temp\\heapdumps\\dump.bin", pid };
Process p = Runtime.getRuntime().exec(cmd);

5. HotSpotDiagnosticMXBean
This option is available in Java 1.6+ and uses

ManagementFactory.getDiagnosticMXBean().dumpHeap("D:\\temp\\heapdumps\\dump.bin", true);

When we get the heap dump we need to use a tool like VisualVM (also included in JDK installation)to actually try and find the leak.
There are of course a lot of different tools, free and commercial, that can provide monitoring and creating of heap dumps. But in some cases there are restrictions in including 3rd party tools in the picture and that is where this list comes in.