What are the young, old and Metaspace areas in the Java heap?
The heap is split into parts, and each part is used for a different kind of object.
The young generation is where almost every new object is made. It has three parts. The eden space is where the objects are put when they are created. The two survivor spaces hold the objects that have already survived one collection, and the collections alternate between them so that the space can be copied to.
The old generation, which is also called the tenured generation, holds the objects that have been alive for a long time. An object gets moved here when it has survived enough collections in the young generation.
Metaspace is not part of the heap at all. It holds the information about the classes themselves, and it lives in the memory of the operating system rather than in the Java heap.
public class Main {
public static void main(String[] args) {
Runtime runtime = Runtime.getRuntime();
long max = runtime.maxMemory();
long total = runtime.totalMemory();
long free = runtime.freeMemory();
System.out.println("the maximum heap MB : " + (max / (1024 * 1024)));
System.out.println("the reserved heap MB: " + (total / (1024 * 1024)));
System.out.println("the free heap MB : " + (free / (1024 * 1024)));
System.out.println("the used heap MB : " + ((total - free) / (1024 * 1024)));
}
}
The reason for the split is that most objects die young. The great majority of the objects that you make are finished with almost at once, and so the collector can get rid of them cheaply, as long as they are in one part of the heap where it does not have to look at the whole thing.
The next question in this topic looks at how the collector works in the young part.