Can you explain all garbage collectors up to Java's latest stable release?

Garbage Collectors (GCs) in Java automatically reclaim memory occupied by objects that are no longer reachable, helping prevent memory leaks and reducing manual memory management. Over the years, Java has introduced several garbage collectors optimized for different goals such as throughput, low latency, scalability, and large heap management.

Key Points: • Different garbage collectors are designed for different workloads, ranging from small applications to large enterprise systems with terabytes of memory. • Modern Java versions primarily use G1 GC, ZGC, and Shenandoah GC, while older collectors such as CMS have been deprecated or removed. • Choosing the right GC depends on application requirements such as throughput, response time, pause-time sensitivity, and heap size.

Types of Garbage Collectors:

1. Serial GC • Uses a single thread for garbage collection. • Suitable for small applications and single-CPU environments. • Prioritizes simplicity over scalability.

JVM Option: -XX:+UseSerialGC

2. Parallel GC (Throughput GC) • Uses multiple threads for garbage collection. • Focuses on maximizing application throughput. • Suitable for batch processing and CPU-intensive workloads.

JVM Option: -XX:+UseParallelGC

3. CMS (Concurrent Mark Sweep) GC • Designed to minimize pause times. • Performs most garbage collection work concurrently with application threads. • Deprecated in Java 9 and removed in Java 14.

JVM Option: -XX:+UseConcMarkSweepGC

4. G1 GC (Garbage First) • Divides the heap into regions and collects them intelligently. • Balances throughput and low pause times. • Default garbage collector since Java 9.

JVM Option: -XX:+UseG1GC

5. ZGC (Z Garbage Collector) • Designed for ultra-low pause times. • Supports very large heaps ranging from gigabytes to terabytes. • Pause times are typically measured in milliseconds regardless of heap size.

JVM Option: -XX:+UseZGC

6. Shenandoah GC • Focuses on low-latency applications. • Performs most heap evacuation concurrently. • Keeps pause times predictable even with large heaps.

JVM Option: -XX:+UseShenandoahGC

7. Epsilon GC • A no-op garbage collector. • Does not reclaim memory. • Useful for performance testing, benchmarking, and memory analysis.

JVM Option: -XX:+UseEpsilonGC

Example: A banking application requiring high throughput may use Parallel GC, while a real-time trading platform requiring very low latency would typically choose ZGC or Shenandoah GC to minimize pause times.

Interview Tip: A concise interview answer is: Java provides several garbage collectors, including Serial GC, Parallel GC, CMS GC, G1 GC, ZGC, Shenandoah GC, and Epsilon GC. G1 GC is the default collector in modern Java versions, while ZGC and Shenandoah are preferred for ultra-low latency applications. The choice of GC depends on whether the priority is throughput, low pause times, or scalability for large heaps.