JVM.Advanced.What is the purpose of the Metaspace in JVM?

The Metaspace in the JVM (Java Virtual Machine) is a memory space that was introduced in Java 8, replacing the older PermGen space. Its primary purpose is to store class metadata, which includes information about class structures, methods, fields, annotations, and other class-related data.


🧰 Key Purposes of Metaspace:

1. Storage of Class Metadata

  • Every time a class is loaded by the ClassLoader, the metadata of that class (like method names, field types, method bytecode, annotations, etc.) is stored in Metaspace.
  • This is especially important in applications that dynamically load and unload classes (like app servers or frameworks that support hot deployment).

2. Decoupling from Heap

  • Unlike PermGen, which was part of the JVM heap, Metaspace is native memory (outside of the heap).
  • This means it uses memory directly from the operating system rather than being managed within the JVM heap.
  • This improves flexibility, as you are no longer bound by a fixed-sized PermGen.

3. Automatic Growth (but Configurable)

  • Metaspace can grow dynamically as needed, limited only by the available system memory (or optionally by configurable JVM flags like MaxMetaspaceSize).
  • In PermGen, you had to manually configure the size (-XX:MaxPermSize), and if you hit that limit, you would get OutOfMemoryError: PermGen space.

4. ClassLoader Lifespan Management

  • Each ClassLoader gets its own chunk in Metaspace.
  • When a ClassLoader is garbage collected, its associated classes and metadata are also cleaned up from Metaspace.
  • This helps reduce memory leaks in applications that rely heavily on class reloading (like web servers).

5. Better Tuning Options

  • You can tune Metaspace with flags like:
    • -XX:MetaspaceSize (initial size)
    • -XX:MaxMetaspaceSize (maximum size, optional)
    • -XX:MetaspaceFreeRatio (tuning how much free space to maintain)

🔗 Summary

AspectMetaspacePermGen
LocationNative memory (outside heap)Part of JVM heap
SizingGrows dynamically by defaultFixed, must be pre-set
Use caseClass metadata storageClass metadata storage
GC behaviorCleared when ClassLoader unloadedCleared when GC happens
Config optionsFlexible (MetaspaceSize, MaxMetaspaceSize)PermSize, MaxPermSize

🚨 Why was PermGen removed?

  • PermGen was a frequent source of OutOfMemoryError in large apps.
  • It was hard to tune correctly.
  • It included both class metadata and some runtime data (like interned Strings), which made it difficult to manage efficiently.
  • Metaspace is more efficient, more flexible, and less prone to memory leaks caused by class loading.
This entry was posted in Без рубрики. Bookmark the permalink.