title: Java G1: Monitoring for memory leaks in production
body: <p>For years, we've been running Java services with modest heap sizes using <code>+UseParallelOldGC</code>. Now, we're starting to roll out a new service using a larger heap and the G1 collector. This is going pretty well.</p>
  
  <p>For our services that use <code>+UseParallelOldGC</code>, we monitor for memory leaks by looking at the old generation size after collection and alerting on a threshold. This works quite well, and in fact saved our bacon just two weeks ago.</p>
  
  <p>Specifically, for <code>+UseParallelOldGC</code>, we do the following:</p>
  
  <ul>
  <li><code>ManagementFactory.getMemoryPoolMXBeans()</code></li>
  <li>Search for the <code>MemoryPoolMXBean</code> result with the name ending in <code>"Old Gen"</code></li>
  <li>Compare <code>getCollectionUsage().getUsed()</code> (if available) with <code>getMax()</code></li>
  </ul>
  
  <p>Unfortunately, it seems like G1 no longer has a concept of <code>getCollectionUsage()</code>.</p>
  
  <p>Fundamentally, though, we'd like to monitor the G1 heap size following the last mixed collection it chooses to do in a mixed cycle, or something similar.</p>
  
  <p>For example, outside the VM I would be happy with an awk script that merely found the last <code>'(mixed)'</code> was that's followed by a <code>'(young)'</code> and look what the final heap size was (e.g., <code>'1540.0M' 'Heap: 3694.5M(9216.0M)-&gt;1540.0M(9216.0M)'</code>)</p>
  
  <p>Is there any way to do this inside the Java VM?</p>