Aquire and Inspect Java Memory Dumps

Here are some straighforward steps for aquiring a memory dump and simple tools for inspecting. This method works well because the tools needed are packaged right with the JDK. Great if you find yourself with memory issues or stuck threads on a remote server.

Starting with a simple example

Here's a small program I wrote which creates two thread which allocate a few MB of memory. I placed an infinite loop at the bottom in order to keep the threads alive.

package net.largepixels.examples.threading.memorydumptest;
import java.util.Vector;
/**
* Created by johnminchuk on 3/23/17.
*/
public class MemoryDumpExample {
class ThreadA implements Runnable {
@Override
public void run() {
Vector vectorA = new Vector();
for (int i = 0; i < 10000; i++) {
byte b[] = new byte[1024];
vectorA.add(b);
}
while (true) {
//keep this thread around...
}
}
}
class ThreadB implements Runnable {
@Override
public void run() {
Vector vectorB = new Vector();
for (int i = 0; i < 5000; i++) {
byte b[] = new byte[1024];
vectorB .add(b);
}
while (true) {
//keep this thread around...
}
}
}
private void runMe() {
Thread a = new Thread(new ThreadA());
Thread b = new Thread(new ThreadB());
a.start();
b.start();
while (true) {
//keep this thread around...
}
}
public static void main(String args[]) {
MemoryDumpExample memoryDumpExample = new MemoryDumpExample();
memoryDumpExample.runMe();
}
}

Aquire the memory dump

Let's launch the program.

$ pwd
/Users/johnminchuk/Development/CodeExamples/target/classes
$ java -cp ./ net.largepixels.examples.threading.memorydumptest.MemoryDumpExample

And use jmap to dump it.

$ jps | grep MemoryDumpExample
79101 MemoryDumpExample
$ jmap -dump:format=b,file=dump.bin 79101

Inspect the dump

Another program built into the JDK is jhat, which will launch a server on port 700 to view the dump.

$ jhat dump.bin 
Reading from dump.bin...
Dump file created Thu Mar 23 10:10:08 CDT 2017
Snapshot read, resolving...
Resolving 211833 objects...
Chasing references, expect 42 dots..........................................
Eliminating duplicate references..........................................
Snapshot resolved.
Started HTTP server on port 7000
Server is ready.

You can now view the dump in your browser. The only problem with this method is, the dumps can be huge, and finding an issue is like trying to find a needle in a haystack.

For a more comprehensive look, try out Eclipse Memory Analyizer (MAT). From the Overview page try clicking on the Dominator Tree. Here you can easily see thread A and thread B and the amount of memory they consuem. Drilling down into B you can see the Vector and all the bytes stored in it.