Sub topic 8
Metaspace and Class Metadata
This chapter assumes you know basic Java syntax, objects, references, and how to run Java programs from the command line. It focuses on Java 11 and later HotSpot JVMs.
What Metaspace stores
Metaspace is native memory used by the JVM to store class metadata. Class metadata describes classes rather than ordinary object data. It includes information such as:
- The class name and superclass
- Field and method descriptions
- Bytecode and constant-pool information
- Runtime annotations
- Method dispatch data
- Information needed by reflection and class loading
The objects created with new usually live in the Java heap. The descriptions of their classes are stored in Metaspace.
Before Java 8, HotSpot stored class metadata in a heap area called PermGen, or permanent generation. Java 8 removed PermGen and replaced it with Metaspace. This change lets class metadata grow in native memory instead of using a fixed heap region.
Metaspace is outside the Java heap, but it is still managed by the JVM. Therefore, a process can run out of native memory because of Metaspace even when the Java heap has free space.
Class loaders control class lifetime
A class loader loads a class and associates that class with the loader. In the JVM, a class is identified by both its fully qualified name and its defining class loader.
For example, two class loaders can load com.example.Plugin separately. The JVM treats the resulting classes as different types, even though their names match.
Metaspace can be reclaimed when a class loader becomes unreachable and the JVM unloads the classes defined by that loader. Class unloading usually occurs during a major or full garbage collection. A class loader that remains reachable keeps its classes and their metadata alive.
Common causes of class-loader retention include:
- A static field referring to a plugin class or object
- A running thread whose context class loader is the old loader
- A listener or timer registered with a long-lived service
- A cache that uses class objects as keys
- Thread-local values left behind by a plugin
- Dynamically generated classes that are never discarded
Inspecting class loading and memory pools
The following program reports loaded-class counts and memory pools whose names contain Metaspace or Compressed Class Space. Pool names can vary between JVM implementations, so the program checks names instead of assuming one exact layout.
import java.lang.management.ClassLoadingMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.util.List;
public class MetaspaceInfo {
public static void main(String[] args) {
ClassLoadingMXBean classes =
ManagementFactory.getClassLoadingMXBean();
System.out.println("Loaded classes: " + classes.getLoadedClassCount());
System.out.println("Total loaded: " + classes.getTotalLoadedClassCount());
System.out.println("Unloaded classes: " + classes.getUnloadedClassCount());
List<MemoryPoolMXBean> pools =
ManagementFactory.getMemoryPoolMXBeans();
for (MemoryPoolMXBean pool : pools) {
String name = pool.getName();
if (name.contains("Metaspace")
|| name.contains("Compressed Class Space")) {
System.out.println(name);
System.out.println(" used: " + pool.getUsage().getUsed());
System.out.println(" committed: " + pool.getUsage().getCommitted());
System.out.println(" max: " + pool.getUsage().getMax());
}
}
}
}The class-loading counters are useful for spotting trends. If loaded classes continually increase during repeated deployments, investigate whether old class loaders are still reachable.
Limits and failure modes
The JVM can control Metaspace with options such as:
java -XX:MetaspaceSize=64m -XX:MaxMetaspaceSize=256m MetaspaceInfoMetaspaceSize is an initial threshold that can influence when metadata collection starts. It is not a hard initial allocation. MaxMetaspaceSize sets an upper limit. If the JVM cannot allocate more metadata below that limit, it can report:
java.lang.OutOfMemoryError: MetaspaceThe compressed class space is a related native-memory area used when compressed class pointers are enabled. Its limit can be adjusted with -XX:CompressedClassSpaceSize, but increasing it does not fix a class-loader leak.
Use limits to contain damage, not to hide the cause. First determine whether the application loads too many classes or retains obsolete class loaders.
Exercise
Why can a class loader leak cause OutOfMemoryError: Metaspace even when the Java heap is not full?
Show answer
A reachable class loader keeps its class metadata alive in native Metaspace, so Metaspace can reach its limit independently of heap occupancy.