title: Java8 metaspace & heap usage
body: <p>I have this code to generate class dynamically and load it </p>
  
  <pre><code>import javassist.CannotCompileException;
  import javassist.ClassPool;
  
  public class PermGenLeak {
      private static final String PACKAGE_NAME = "com.jigarjoshi.permgenleak.";
  
      public static void main(String[] args) throws CannotCompileException, InterruptedException {
          for (int i = 0; i &lt; Integer.MAX_VALUE; i++) {
              ClassPool pool = ClassPool.getDefault();
              pool.makeClass(PACKAGE_NAME + i).toClass();
              Thread.sleep(3);
          }
  
      }
  }
  </code></pre>
  
  <p>I launched this class against Java 7 (jdk1.7.0_60) and as expected it filled up PermGenSpace and heap remained unused <img src="https://i.stack.imgur.com/1XlmX.png" alt="Java 7 memory usage">
  <sub>image shows permgen usage overtime and at the end JVM was terminated</sub></p>
  
  <p>Now the same code ran against Java 8 (jdk1.8.0_40-ea) and as expected it kept expanding native memory (Metaspace) but surprisingly for 1g of Metaspace it consumed 3g of Heap in OldGen (almost 3x of Metaspace maintained over time)</p>
  
  <p><img src="https://i.stack.imgur.com/2yYvD.png" alt="Java8 memory usage">
  <sub>image shows Metaspace  usage overtime and System memory usage sample</sub></p>
  
  <p><a href="http://mail.openjdk.java.net/pipermail/hotspot-dev/2012-September/006679.html" rel="noreferrer">this email from Jon Masamitsu</a> and <a href="http://openjdk.java.net/jeps/122" rel="noreferrer">this JEP ticket</a> says </p>
  
  <blockquote>
    <p>interned <code>String</code> and Class stats and some misc data has been moved to Heap</p>
  </blockquote>
  
  <p>what exactly makes this increase in heap as it loads more classes into Metaspace ?</p>