Java Memory Layout and Garbage Collection Principles
This article provides a comprehensive overview of the JVM runtime memory areas, explains how the JVM determines garbage objects, reviews major GC algorithms and collectors—including the latest ZGC—and offers practical code examples and command‑line instructions for reproducing various OutOfMemoryError scenarios.
Java developers frequently encounter questions about JVM memory layout and garbage collection (GC), which are also common interview topics.
The article begins by describing the JVM runtime data areas defined in the Java 8 specification, dividing them into thread‑local regions (PC register, JVM stack, native method stack) and shared regions (heap, method area, runtime constant pool), and mentions off‑heap memory managed via Unsafe and DirectByteBuffer .
It then explains how the JVM decides whether an object is garbage, covering reference‑counting and reachability analysis, and clarifies which memory regions are subject to GC (heap and method area) while others (PC register, stacks) are not.
The article reviews the classic GC algorithms: mark‑sweep, mark‑copy, mark‑compact and generational collection, illustrating each with diagrams and discussing their trade‑offs such as fragmentation and pause times.
Next, it enumerates the seven traditional collectors (Serial, ParNew, Parallel Scavenge, Serial Old, Parallel Old, CMS, G1) and introduces the newest ZGC, detailing its innovations like dynamically sized regions, colored pointers, load barriers, relocation, multi‑mapping, and NUMA support, as well as its sub‑10 ms pause goal.
A practical section provides a small OOMTest program that can trigger heap, stack, metaspace and off‑heap OutOfMemoryError conditions. The article supplies command‑line examples for OpenJDK 11 with G1 and OpenJDK 8 with CMS, showing the expected GC log snippets and error messages.
It also mentions the open‑source GCViewer tool for visualizing GC logs and includes a curated list of reference links for deeper study.
import sun.misc.Unsafe;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public class OOMTest {
public static void main(String[] args) {
OOMTest test = new OOMTest();
//heap OOM test
//test.heapOOM();
//stack overflow test
//test.stackOverflow();
//metaspace OOM test
//test.metaspaceOOM();
//off‑heap OOM test
//test.directOOM();
}
/** heap OOM test */
public void heapOOM() {
List
list = new ArrayList<>();
while (true) {
list.add(new OOMTest());
}
}
private int stackLength = 1;
public void stackLeak() {
stackLength += 1;
stackLeak();
}
/** VM Stack / Native method Stack overflow test */
public void stackOverflow() {
OOMTest test = new OOMTest();
try {
test.stackLeak();
} catch (Throwable e) {
System.out.println("stack length:" + test.stackLength);
throw e;
}
}
public void genString() {
List
list = new ArrayList<>();
int i = 0;
while (true) {
list.add("string-" + i);
i++;
}
}
/** metaspace / constant pool OOM test */
public void metaspaceOOM() {
OOMTest test = new OOMTest();
test.metaspaceOOM();
}
public void allocDirectMemory() {
final int _1MB = 1024 * 1024;
Field unsafeField = Unsafe.class.getDeclaredFields()[0];
unsafeField.setAccessible(true);
Unsafe unsafe = null;
try {
unsafe = (Unsafe) unsafeField.get(null);
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
while (true) {
unsafe.allocateMemory(_1MB);
}
}
/** off‑heap OOM test */
public void directOOM() {
OOMTest test = new OOMTest();
test.allocDirectMemory();
}
} [1.892s][info][gc] GC(42) Concurrent Cycle 228.393ms
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.base/java.util.Arrays.copyOf(Arrays.java:3689)
...
[1.895s][info][gc,heap,exit] Heap [0.821s][info][gc] GC(4) Pause Young (Normal) (G1 Evacuation Pause) 12M->7M(20M) 5.245ms
stack length:1699
Exception in thread "main" java.lang.StackOverflowError
at oom.OOMTest.stackLeak(OOMTest.java:45)
...Ctrip Technology
Official Ctrip Technology account, sharing and discussing growth.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.