In Java, the Metaspace
and PermGen
spaces are used to store class metadata and other class-related data.
PermGen
(short for "Permanent Generation") is a space in the Java Heap that was used to store class metadata in Java versions up to Java 8. PermGen
was a fixed-size space, meaning that the amount of space allocated to it was predetermined at the time the Java Virtual Machine (JVM) was started. If the PermGen
space filled up, it would trigger a java.lang.OutOfMemoryError
, and the JVM would crash.
The default maximum memory size for 32-bit JVM is 64 MB and 82 MB for the 64-bit version.
However, we can change the default size with the JVM options:
- -XX:PermSize=[size] is the initial or minimum size of the PermGen space
- -XX:MaxPermSize=[size] is the maximum size
With its limited memory size, PermGen is involved in generating the famous OutOfMemoryError. Simply put, the class loaders weren’t garbage collected properly and, as a result, generated a memory leak.
In Java 8, PermGen
was replaced with Metaspace
, which is a native memory space that is not part of the Java heap (Non-Heap Memory Area). Metaspace
is not fixed in size and can dynamically expand as needed. When the Metaspace
space becomes full, the JVM will attempt to allocate more native memory to it. If the operating system is unable to provide the requested amount of memory, the JVM will throw an OutOfMemoryError
.
One key difference between PermGen
and Metaspace
is that PermGen
space was garbage collected, while Metaspace
is not. This means that in PermGen
, objects that were no longer being used would eventually be cleaned up and the space they occupied would be made available for new objects. In Metaspace
, however, unused class metadata will remain in memory until the JVM is shut down.
In summary, Metaspace
and PermGen
are both used to store class metadata in the JVM, but PermGen
was a fixed-size space in the Java heap while Metaspace
is a native memory space that can dynamically expand as needed. PermGen
was also garbage collected, while Metaspace
is not.