Lesson 11 / 38

Memory & Garbage Collection

Understand the stack, the heap and reachability, how generational collectors like G1, ZGC and Shenandoah work, and how leaks still happen under a GC.

Stack vs heap

Each thread has a stack of frames holding local variables and references. All objects live on the shared heap. An object is eligible for collection when it is no longer reachable from any GC root (stack, statics, JNI).

Generational collectors

Most objects die young, so the heap is split into young and old generations. G1 (default) targets pause-time goals; ZGC and Shenandoah aim for sub-millisecond pauses on large heaps. Tune with -Xmx, -Xms, and a collector flag — measure first.

Memory leaks in a GC language

You can still leak: objects kept in a static collection, unbounded caches, unremoved listeners, or ThreadLocals never cleared. Reachable but unused = leak.