Topic 17 of 30 · Expert
JVM Memory & Garbage Collection
Heap, stack, metaspace and how GC reclaims memory.
Concept
Each thread has a stack holding method frames and local primitives/references. Objects live on the shared heap. Class metadata lives in Metaspace.
The heap is generational: new objects go to the Young generation (Eden + Survivor spaces); long-lived ones are promoted to the Old generation.
Garbage collectors (G1 default, ZGC for low latency) reclaim unreachable objects. Memory leaks still happen when references are kept — e.g. static collections that keep growing.
Cheat sheet
| Area | Stores | Error when full |
|---|---|---|
| Stack | Frames, locals | StackOverflowError |
| Heap | Objects | OutOfMemoryError: Java heap space |
| Metaspace | Class metadata | OutOfMemoryError: Metaspace |
Code (Java 21)
// JVM flags
// java -Xms512m -Xmx2g -XX:+UseG1GC -Xlog:gc App
static final List<byte[]> CACHE = new ArrayList<>();
static void leak() {
CACHE.add(new byte[1024 * 1024]); // never removed -> leak
}
// Weak references let GC reclaim values
Map<Object, String> meta = new WeakHashMap<>();Remember
- Objects are reachable from GC roots or collectable.
- System.gc() is only a hint.
- -Xmx sets max heap.
Interview questions
Can Java have memory leaks?
Yes — when objects are no longer needed but still referenced, e.g. growing static maps, unclosed resources or listeners never removed.
Explain the generational heap.
Most objects die young, so the Young gen is collected often and cheaply. Survivors are promoted to the Old gen, collected less often.
Lesson test
Take an 8-question test on “JVM Memory & Garbage Collection” — concepts, output prediction, bug spotting and interview questions.