In Java 8, PermGen space on the heap is replaced by Metaspace on native memory. The main difference between them is, Metaspace by default auto increases its size up to the memory provided by the Operating System, while PermGen always had a fixed maximum size. So, there will be fewer chances to get the OutOfMemoryError.
When PermGen was initially introduced there was no dynamic class loading/unloading, so when the class was loaded it was there in PermGen until JVM shuts down. These days classes may be loaded/unloaded during the lifespan of JVM, so Metaspace makes more sense for the area where metadata is stored.
Difference between PermGen and Metaspace:
-
- PermGen had a fixed maximum size by default, where Metaspace size auto increases by default.
- PermGen max size can be changed using -XX:MaxPermSize option and Metaspace maximum size can also be fixed using XX:MaxMetaspaceSize.
- PermGen has comparatively inefficient garbage collection – frequent pauses and no concurrent deallocation. Where, Metaspace has comparatively efficient garbage collection – deallocated class data concurrently and not during GC pause.
Metaspace garbage collection
- Garbage collection of the dead classes and classloaders is triggered once the class metadata usage reaches the “MaxMetaspaceSize”.
- Proper monitoring & tuning of the Metaspace will obviously be required in order to limit the frequency or delay of such garbage collections. Excessive Metaspace garbage collections may be a symptom of classes, classloader memory leak or inadequate sizing for your application.
There were few new flags added in Java 8 for Metaspace:
- -XX:MetaspaceSize=<NNN>
Where <NNN> is the initial amount of space (initial high-water mark) allocated (in bytes)for class metadata that may induce a garbage collection to unload classes. After the amount of first high-water mark reached, the next high-water mark is managed by the garbage collector. - -XX:MaxMetaspaceSize=<NNN>
Where <NNN> is the maximum amount of space allocated for class metadata (in bytes). This flag can be used to limit the amount of space allocated for class metadata, by default, there is no limit. - -XX:MinMetaspaceFreeRatio=<NNN>
Where <NNN> is the minimum percentage of class metadata capacity free after a GC to avoid an increase in the amount of space (high-water-mark) allocated for class metadata that will induce a garbage collection. - -XX:MaxMetaspaceFreeRatio=<NNN>
Where <NNN> is the maximum percentage of class metadata capacity free after a GC to avoid a reduction in the amount of space (high-water-mark) allocated for class metadata that will induce a garbage collection.
Note: Metaspace size auto increases in native memory as required to load class metadata if not restricted with -XX:MaxMetaspaceSize, It can bring down the whole server if not restricted. Be cautious to define this limit, so that we can avoid memory wastage.