Friday, May 01, 2009

A better way of printing heap usage in Java

If you rely on getting the heap usage by methods provided in Runtime, then consider making use of the MemoryPoolMXBeans. The code to print the memory usage is extremely simple:
List mpool = ManagementFactory.getMemoryPoolMXBeans();
for(MemoryPoolMXBean b:mpool) {
System.out.println(b.getName() + ": " + b.getUsage());
You will see something like this when you run this:
Code Cache: init = 163840(160K) used = 468672(457K) committed = 491520(480K) max = 33554432(32768K)
Eden Space: init = 917504(896K) used = 202792(198K) committed = 917504(896K) max = 4194304(4096K)
Survivor Space: init = 65536(64K) used = 0(0K) committed = 65536(64K) max = 458752(448K)
Tenured Gen: init = 4194304(4096K) used = 0(0K) committed = 4194304(4096K) max = 61997056(60544K)
Perm Gen: init = 12582912(12288K) used = 108360(105K) committed = 12582912(12288K) max = 67108864(65536K)
Perm Gen [shared-ro]: init = 8388608(8192K) used = 6162160(6017K) committed = 8388608(8192K) max = 8388608(8192K)
Perm Gen [shared-rw]: init = 12582912(12288K) used = 7282024(7111K) committed = 12582912(12288K) max = 12582912(12288K)
This is a lot more informative than the information provided by the Runtime. This works only in versions 1.5 or later.

No comments: