πŸ“Œ What is Metaspace?

  • Memory region (outside the Java heap, in native memory).
  • Stores class metadata: method tables, field info, constant pools, vtables, and class loader structures.
  • Introduced in Java 8, replacing PermGen.

πŸ“… When is it used?

  • At class loading time, when a new class is loaded by a class loader.
  • Each class has its metadata allocated inside the loader’s Metaspace.
  • Static fields are stored in heap, but metadata (e.g., methods, structure) β†’ Metaspace.

❓ Why Metaspace?

  • PermGen problem: fixed size β†’ frequent OutOfMemoryError: PermGen space.
  • Metaspace advantage: grows dynamically, limited by system memory or -XX:MaxMetaspaceSize.
  • Memory can be reclaimed if the class loader is GC’d.

πŸ”‘ Key Point

  • Classes loaded by bootstrap/system loaders β†’ live for the life of JVM.
  • Classes loaded by custom loaders (e.g., Tomcat, OSGi) β†’ freed when loader is GC’d.