Rolling Your Own Java Memory Profiler

I was looking around for some code to build a unit test for easy tests to isolate various aspects or collaborators in an application and after trying a couple of solutions that didn’t seem right, I found, “Do you know your data size?” By Vladimir Roubtsov, Its impossible to do any basic true tests because, and I like that he brings up these points:

  • A single call to Runtime.freeMemory() proves insufficient because a JVM may decide to increase its current heap size at any time (especially when it runs garbage collection). Unless the total heap size is already at the -Xmx maximum size, we should use Runtime.totalMemory()-Runtime.freeMemory() as the used heap size.
  • Executing a single Runtime.gc() call may not prove sufficiently aggressive for requesting garbage collection. We could, for example, request object finalizers to run as well. And since Runtime.gc() is not documented to block until collection completes, it is a good idea to wait until the perceived heap size stabilizes.
  • If the profiled class creates any static data as part of its per-class class initialization (including static class and field initializers), the heap memory used for the first class instance may include that data. We should ignore heap space consumed by the first class instance.

The basic idea is Runtime.totalMemory()-Runtime.freeMemory() as the used heap size. Vladimir includes the code and I’ll post my junit test soon which simplifies this.


Leave a Reply