Friday, May 29, 2009

Poor Man's Java memory profiler

Here is an example of do-it-yourself memory profiling e.g. showing used heap memory over the life of a program run. I compared it with results from YourKit to convince myself it's ok.

The concept:
  • Launch a separate thread that collects used memory stats
  • add a shutdown hook to output the stats


Here's an example in a Junit test...
public class CacheRebuildReloadTest extends RollbackTestCase {
private static int j = 0;
private static final long t0 = System.currentTimeMillis();
private static long t[] = new long[32767];
private static long m[] = new long[32767];
private static Runtime r = Runtime.getRuntime();
private static boolean done = false;
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
for (int i = 0; i < j; i++) {
System.out.println(t[i] + "\t" + m[i]);
}
}
});
new Thread() {
public void run() {
while (!done) {
t[j] = System.currentTimeMillis() - t0;
m[j++] = r.totalMemory() - r.freeMemory();
try {Thread.sleep(500);} catch (Exception e) {}
if (j > 32767) {done = true;}
}
}
}.start();
}
public void testRebuildReload() {
// stuff here
done = true;
}
}

Here is a comparison with a YourKit memory profile (and a plot of the 2 sampling frequencies and distributions - I used .5s and YourKit apparently 1s). Good enough for my purposes.

No comments: