Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is heap memory going up together with metaspace in Java 8?

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:

enter image description here

enter image description here

like image 656
Andre Avatar asked May 18 '18 15:05

Andre


People also ask

Is Metaspace part of heap memory?

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.

What is the exact reason of replacing PermGen memory with Metaspace in java8?

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.

Why does heap size increase?

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.

Is Metaspace part of XMX?

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.


1 Answers

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.

like image 104
Sean F Avatar answered Nov 15 '22 21:11

Sean F