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 Area | What it Stores |
|---|---|
| Heap | All objects and class instances |
| Stack | Method calls and local variables |
| Method Area | Class metadata, static fields |
| GC only runs on the Heap โ thatโs where it reclaims memory. |
๐ธ How GC Works (Conceptually)
-
JVM runs GC on a background thread
-
GC finds all reachable objects
-
Everything else is marked as โgarbageโ
-
Unreachable objects are freed and heap space is reclaimed
๐น Java GC Algorithm (Modern JVM: HotSpot)
๐ Generational GC
Heap is divided into generations:
| Generation | Description |
|---|---|
| Young Generation | Where new objects are created. GC runs frequently (Minor GC) |
| Old Generation (Tenured) | Where long-lived objects are promoted. GC runs less frequently (Major GC) |
| Metaspace | Stores class metadata (replaced PermGen in Java 8+) |
Most objects die young โ Minor GC is optimized to be fast.
๐ง Common GC Collectors
| GC Type | Description |
|---|---|
| Serial GC | Single-threaded. Good for small apps |
| Parallel GC | Multi-threaded, throughput-focused |
| G1 GC (default since Java 9) | Splits heap into regions. Balances pause time and throughput |
| ZGC, Shenandoah | Low-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?