Garbage Collection
Java's garbage collector (GC) automatically manages heap memory by identifying and
reclaiming space from objects no longer in use, freeing developers from manual
deallocation.
Garbage Collection Basics
Garbage collection in Java runs within the JVM, targeting unreachable objects—those
without active references from roots like local variables, static fields, or threads
The process prevents memory leaks by periodically scanning the heap, which is divided into
young (Eden and Survivor spaces) and old generations for efficiency.
GC is non-deterministic; it activates based on heap pressure, not on demand, though
[Link]() can suggest it (no guarantee).
Full GC Process
Java primarily uses a mark-and-sweep algorithm, often with compaction, executed in these
phases:
● Mark Phase: Starts from GC roots (stack, statics, registers) and traverses references
to mark live (reachable) objects; unmarked ones are garbage.
● Sweep Phase: Scans the heap to free memory from unmarked objects, adding it
back to the free pool without moving live objects yet.
● Compact Phase (in many collectors): Shifts surviving objects together to reduce
fragmentation and enable faster allocations.
This "stop-the-world" pause halts application threads during GC for consistency.
Generational Collection
Young generation (Eden/Survivors) handles short-lived objects with minor GC (fast,
frequent).
Objects surviving multiple cycles promote to old generation for major/full GC (slower, less
frequent).
Full GC cleans both, often compacting the old gen
Key Collectors
Modern JVMs (HotSpot) offer types like G1 (low-pause, region-based), Parallel
(throughput-focused), and ZGC (ultra-low latency)
Tune via flags like -XX:+UseG1GC for apps needing predictable pauses.
Java Garbage Collector (GC) automatically cleans heap memory, so you don't have to
delete manually – simple explanation for beginners.
What is GC and Why Needed?
In Java, objects use heap memory. When no reference points to an object (no
variable holds it), it becomes "garbage".
GC detects these garbage objects and frees their memory, preventing memory leaks.
You just use new; deletion is automatic – unlike C/C++.
Simple Process (3 Steps)
● Mark: GC starts from roots (like local variables, static vars) and marks live
objects.
● Sweep: Frees memory of unmarked (garbage) objects.
● Compact: Moves live objects together for faster new space allocation.
It causes a brief "stop-the-world" pause (app halts during GC).
Generational Heap
Heap has 2 parts: Young Gen (new objects, fast minor GC) and Old Gen (old objects,
slow full GC).
Most objects (80-90%) die in young gen, keeping it fast.