Garbage Collection Algorithms
Mark-Sweep Algorithm
Characteristics:
- Fast collection speed
- Causes memory fragmentation, making large contiguous allocations difficult
Process:
- First pass marks reachable objects from GC roots
- Second pass sweeps and reclaims memory from marked objects
Mark-Compact Algorithm
Advantages:
- Eliminates memory fragmentation
Disadvantages:
- Slower due to memory compaction
Copy Algorithm
Key Points:
- Divides memory into two equal spaces (From and To)
- Copies live objects from From to To space during collection
- Swaps space designations after collection
Pros/Cons:
- No fragmentation
- Requires double memory space
Algorithm Comparison
| Algorithm | Advantages | Disadvantages |
|---|---|---|
| Mark-Sweep | Fast collection | Memory fragmentation |
| Mark-Compact | No fragmentation | Slower performance |
| Copy | No fragmentation | High memory overhead |
Generational Collection
Heap Strucutre:
- Young Generation: Eden + Survivor spaces (From/To)
- Old Generation: Long-lived objects
Collection Process:
- Objects allocated in Eden
- Minor GC triggers when Eden fills
- Surviving objects copeid to Survivor space
- Objects surviving multiple collections promoted to Old Gen
- Full GC occurs when Old Gen fills
Key Parameters:
-Xms - Initial heap size
-Xmx - Maximum heap size
-Xmn - Young generation size
-XX:SurvivorRatio - Eden/Survivor ratio
-XX:MaxTenuringThreshold - Promotion threshold
Garbage Collectors
Serial Collector
- Single-threaded
- Suitable for small heaps
- Flags:
-XX:+UseSerialGC
Throughput-Optimized Collector
- Parallel collection
- Maximizes application throughput
- Flags:
-XX:+UseParallelGC
-XX:GCTimeRatio
-XX:MaxGCPauseMillis
Low-Pause Collector (CMS)
- Concurrent marking
- Minimizes pause times
- Flags:
-XX:+UseConcMarkSweepGC
-XX:ConcGCThreads
-XX:CMSInitiatingOccupancyFraction
CMS Workflow:
- Initial mark (STW)
- Concurrent marking
- Remark (STW)
- Concurrent sweep