Java handles garbage collection (GC) automatically through a managed memory system that frees developers from manual memory management. Here's how it works:
Core Concepts
Automatic Memory Management: Java automatically identifies and removes objects that are no longer reachable or referenced by any part of the program, freeing up memory for reuse.
Heap Structure: The Java heap is typically divided into generations:
- Young Generation: Where new objects are allocated
- Eden Space: Initial allocation area
- Survivor Spaces (S0, S1): Objects that survive initial GC
- Old Generation (Tenured): Long-lived objects that survived multiple GC cycles
- Metaspace (Java 8+): Stores class metadata (replaced PermGen)
How It Works
Mark and Sweep Process:
- Mark Phase: GC identifies all objects reachable from "GC roots" (active threads, static variables, JNI references)
- Sweep Phase: Unreachable objects are removed and memory is reclaimed
- Compaction (optional): Memory is defragmented to reduce fragmentation
Generational Collection: Based on the observation that most objects die young:
- Minor GC: Collects young generation frequently
- Major/Full GC: Collects entire heap less frequently
Common Garbage Collectors
Serial GC: Single-threaded, suitable for small applications
-XX:+UseSerialGC
Parallel GC: Multi-threaded, default for many JVMs
-XX:+UseParallelGC
G1GC (Garbage First): Low-latency collector for large heaps
-XX:+UseG1GC
ZGC/Shenandoah: Ultra-low latency collectors (millisecond pauses)
-XX:+UseZGC
Key Points
When GC Runs:
- Automatically when heap fills up
- Can be suggested (not forced) via
System.gc()
- Different triggers for different generations
Object Eligibility:
- Objects become eligible when no strong references exist
- Reference types affect eligibility (Strong, Weak, Soft, Phantom)
Performance Considerations:
- GC pauses can affect application performance
- Tuning involves balancing throughput vs. latency
- Monitor with tools like JVisualVM, JConsole, or GC logs
Best Practices:
- Minimize object creation in hot paths
- Use object pools for expensive objects
- Size heap appropriately (-Xmx, -Xms)
- Choose appropriate GC algorithm for your use case
Would you like me to dive deeper into any specific aspect of Java's garbage collection?