Core Module
12 min forge
Garbage Collection in Java
Automatic memory management, heap generations, and GC algorithms.
Garbage Collection in Java
π What is it
Garbage Collection (GC) in Java is an automatic process by which the JVM reclaims memory occupied by objects that are no longer reachable by any live thread. This simplifies memory management for developers and prevents most memory leaks.
ποΈ Heap Generations
The Java Heap is divided into generations to optimize GC performance based on the "Infant Mortality" hypothesis (most objects die young).
- Young Generation: Where new objects are allocated. Includes Eden and two Survivor spaces.
- Minor GC: Occurs when Young Gen is full. Fast and frequent.
- Old (Tenured) Generation: Stores long-lived objects that survived multiple Minor GCs.
- Major/Full GC: Occurs when Old Gen is full. Slower and involves a "Stop-the-World" event.
β‘ GC Algorithms
- Serial GC: Single-threaded; good for small apps.
- Parallel GC: Multi-threaded; focuses on high throughput.
- G1 (Garbage First) GC: Designed for high-memory systems; minimizes pause times by dividing heap into regions.
- ZGC / Shenandoah: Modern, ultra-low latency collectors.
π§ Key Concepts
- Stop-the-World (STW): Events when the JVM pauses all application threads to perform GC.
- Mark and Sweep: The basic mechanism where GC "marks" reachable objects and "sweeps" the rest.
β Common mistakes
- Manual
System.gc(): CallingSystem.gc()manually. It's only a hint to the JVM and can lead to performance degradation. - Memory Leak Understanding: Thinking GC prevents all leaks. Objects still reachable (e.g., in a static List) will never be collected.
- Fine-tuning: Over-tuning GC parameters without proper profiling.