# Memory & Garbage Collection — Advanced Java

Source: https://www.geekswithgeeks.com/en/advanced-java/adv-memory-gc

> 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 `ThreadLocal`s never cleared. Reachable but unused = leak.
