Metaspace
- Java course
- Expert
- Lesson 11/46
- 5 min
Learn the class metadata region with Metaspace.
The Metaspace region
Metaspace holds class metadata (method tables, field info, the constant pool). Before Java 8 this was the job of PermGen, whose fixed size caused frequent OutOfMemoryError. Metaspace uses native memory and grows as needed.
When a class is loaded its metadata is written to Metaspace. If many classes are generated dynamically, Metaspace grows; the limit can be set with -XX:MaxMetaspaceSize. Objects themselves still live on the heap; Metaspace holds only class-level information.
The Class object and Metaspace
Every loaded class has a Class object that refers to its metadata in Metaspace. You reach this object with obj.getClass() or Topic.class.
Example: Class<?> c = new Topic().getClass(). Here c.getSimpleName() returns the class's short name; this data comes from Metaspace. Runtime type inspection (reflection) happens through this object. Metaspace grows as the number of classes increases.
Practice Read class metadata
Define a Topic class. In main, get the Class<?> object with new Topic().getClass() and print the getSimpleName() result with System.out.println.
Starter code
// Define the Topic class
// Get the class object with getClass
// Print the name in mainSample solution
class Topic { }
public class MetaspaceDemo {
public static void main(String[] args) {
Class<?> c = new Topic().getClass();
System.out.println(c.getSimpleName());
}
}Expected output
Topic
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the Metaspace concepts
| Term | Meaning |
|---|---|
Metaspace |
Class metadata |
PermGen |
Old region |
getClass() |
Refers to Metaspace |
Stack |
Local variables |
2 What does Metaspace store?
- Objects
- Local variables
- Running threads
- Class metadata Correct answer
Explanation: Metaspace stores class metadata.
3 Get the class name
String name = c.____();
String name = c.getSimpleName();
Explanation: getSimpleName returns the short class name.