I'm doing a little test to understand how metaspace memory (Java 8 onwards) works. When I create 100,000 classes dynamically the metaspace memory is growing (obviously) but heap memory is going up too. Can someone explain to me why this occurs?
PS: I'm running the test with 128 MB of heap and 128 MB of metaspace.
@Test
public void metaspaceTest() throws CannotCompileException, InterruptedException {
ClassPool cp = ClassPool.getDefault();
System.out.println("started");
for (int i = 0; i <= 100000; i++) {
Class c = cp.makeClass("br.com.test.GeneratedClass" + i).toClass();
Thread.sleep(1);
if (i % 10000 == 0) {
System.out.println(i);
}
}
System.out.println("finished");
}
See the images below:
The Metaspace takes up a significant portion of the JVM's Non-Heap memory. Its main purpose is to store class metadata — the internal runtime representation of Java classes. By default, the metaspace is comprised of two parts — the Class Space and the Non-Class Space.
java 8 : PermGen is replaced by Metaspace with the capability to auto increase the native memory as per the requirement to load the class metadata.
To improve the performance of common Delegated Administrator functions such as displaying pages and performing searches, you can increase the Java Virtual Machine (JVM) heap size used by the Web container to which Delegated Administrator is deployed.
The key difference between PermGen and Metaspace is this: while PermGen is part of Java Heap (Maximum size configured by -Xmx option), Metaspace is NOT part of Heap. Rather Metaspace is part of Native Memory (process memory) which is only limited by the Host Operating System.
Your class pool uses heap memory. It's got hashtables and lists and other things. It also uses java reflection code which uses heap memory. Heap memory that is not gc'ed is probably all those data structures in class pool, a couple hashtables, linked lists, array lists, pools, etc... For instance, every single class you create is stored in a hashtable by the class pool. That is a 100,000 element hash table.
Secondly, if there are any static initializers in the classes you are creating, that will use heap memory. Static initializers include the static field initializations and the static block code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With