Garbage Collection is the automatic process of reclaiming memory used by objects that are no longer reachable in your program.

Instead of you manually freeing memory (like in C/C++), the JVM handles it for you.


๐Ÿ”ธ Why Garbage Collection?

  • Prevents memory leaks

  • Prevents dangling pointers

  • Makes Java memory-safe and developer-friendly

โœ… You focus on logic; JVM manages memory lifecycle


๐Ÿ”น When Is an Object Garbage Collected?

An object is eligible for GC when no part of your code can reach it anymore.

Example:

User user = new User();
user = null; // now the original User object is unreachable โ†’ GC eligible

๐Ÿ”น JVM Memory Model for GC

Memory AreaWhat it Stores
HeapAll objects and class instances
StackMethod calls and local variables
Method AreaClass metadata, static fields
GC only runs on the Heap โ€” thatโ€™s where it reclaims memory.

๐Ÿ”ธ How GC Works (Conceptually)

  1. JVM runs GC on a background thread

  2. GC finds all reachable objects

  3. Everything else is marked as โ€œgarbageโ€

  4. Unreachable objects are freed and heap space is reclaimed


๐Ÿ”น Java GC Algorithm (Modern JVM: HotSpot)

๐Ÿ”„ Generational GC

Heap is divided into generations:

GenerationDescription
Young GenerationWhere new objects are created. GC runs frequently (Minor GC)
Old Generation (Tenured)Where long-lived objects are promoted. GC runs less frequently (Major GC)
MetaspaceStores class metadata (replaced PermGen in Java 8+)

Most objects die young โ†’ Minor GC is optimized to be fast.


๐Ÿ”ง Common GC Collectors

GC TypeDescription
Serial GCSingle-threaded. Good for small apps
Parallel GCMulti-threaded, throughput-focused
G1 GC (default since Java 9)Splits heap into regions. Balances pause time and throughput
ZGC, ShenandoahLow-latency, concurrent collectors (Java 11+, 15+)

โœ… TL;DR

Garbage Collection = automatic memory cleanup. JVM tracks which objects are still in use, and reclaims memory from the rest โ€” so you donโ€™t have to manage memory manually.


Want to go deeper into GC tuning, logs, or how to force GC for debugging?