How to query the memory usage stats from the JVM

People using Hibernate and Sun's JVM usually face the java.lang.OutOfMemoryError: PermGen space message sooner or later (mostly sooner Smiling ). To track down the source of an OutOfMemoryError problem you've to be able to query the amount of total and free memory within each available memory pool (heap and non-heap pools as well). Here's a short code snippet to demonstrate how to do that ...

String memoryStats = null;
List<MemoryPoolMXBean> memoryPools = ManagementFactory.getMemoryPoolMXBeans();
if (memoryPools != null) {
  Iterator<MemoryPoolMXBean> memoryPoolIterator = memoryPools.iterator();
  while (memoryPoolIterator.hasNext()) {
    MemoryPoolMXBean pool = memoryPoolIterator.next();
    if (pool != null) {
      MemoryUsage usage = pool.getUsage();
      if (usage != null) {
        memoryStats = (memoryStats != null ? memoryStats + ", " : "") + pool.getName() + " = " + usage.getUsed() + " (" + usage.getMax() + ")";
      }
    }
  }
}

Syndicate content