Metaspace – Class Metadata in Java 8

1. Introduction

Java classes are not saved as it is and have internal representation in JVM. This internal representation is referred to as class metadata. Before Java 8, the class metadata was allocated in space called as “permanent generation“. This permanent generation space is commonly known as Permgen space.

Starting with JDK 8, the permanent generation was removed and the class metadata is allocated in native memory. The space allocated for class metadata is called as Metaspace.

2. Metaspace

Metaspace is the space allocated for class metadata in memory. It is the replacement of Permgen space. Java Hotspot VM manages the space used for metadata and there are ways to configure this Metaspace. By default, there is no limit on the memory which can be allocated to class metadata. Whenever, space is required, it is requested from operating system. The operating system then provides the requested space. The provided space is then divided into chunks. Every chunk is bound to a specific class loader. The class loader allocates space for class metadata from the chunks bound to it. When classes are unloaded for a class loader, the chunks are reused or returned to the operating system. The class metadata can be deallocated if the class is no longer used and unloaded. When the space allocated to the class metadata is used, garbage collector runs to free the space.

Following are few options to work with Metaspace:

  1. -XX:MetaspaceSize: Defines the initial size of Metaspace. Once the usage of Metaspace reaches the level set by this parameter, the garbage collector runs. Note that this is initial allocation and changes dynamically.
  2. -XX:MinMetaspaceFreeRatio and -XX:MaxMetaspaceFreeRatio: Garbage collection runs when the space committed for class metadata reaches a certain level. This level is dynamic in nature. To check whether this threshold level should be increased or decreased depends on the -XX:MinMetaspaceFreeRatio and -XX:MaxMetaspaceFreeRatio.
    If the percentage of committed space available for class metadata out of the total committed space for class metadata is calculated. If this result is greater than -XX:MaxMetaspaceFreeRatio, the threshold level is decreased. Else, if the result is less than -XX:MinMetaspaceFreeRatio, then the threshold level is increased.