What is Metaspace and how is it different from PermGen?
Metaspace stores class metadata and, since Java 8, replaced PermGen. PermGen was a fixed-size part of the heap, while Metaspace uses native memory and grows as needed unless MaxMetaspaceSize is set.
Explain it simply
PermGen was a fixed-size cupboard inside the house for storing class blueprints. When it filled up, nothing more could be stored, even if the house had empty rooms. Metaspace is a store room that can expand into the surrounding plot of land.
Example
Java 7 and earlier:
-XX:MaxPermSize=256m -> OutOfMemoryError: PermGen space
Java 8 and later:
-XX:MaxMetaspaceSize=256m -> OutOfMemoryError: Metaspace
(no limit by default; it is limited by the machine's native memory)What to say in the interview
"Class metadata, such as method definitions and field layouts, lives in Metaspace from Java 8 onward. Unlike PermGen, it is allocated from native memory and resizes automatically, so classic PermGen space errors mostly disappeared. Interned strings and static variables moved to the heap. Metaspace can still run out if a program loads classes endlessly, for example through repeated classloader leaks on redeploys in an application server, so setting MaxMetaspaceSize is a good safety net."
Common mistakes
- Saying Metaspace is part of the heap. It is native memory.
- Assuming memory can never run out in Metaspace because it has no default cap.