Sobes.tech
Senior

What garbage collectors do you know in Java? Are there recommendations for using different types?

sobes.tech AI

Answer from AI

In Java, there are several main garbage collectors, each optimized for different scenarios and performance requirements:

  • Serial GC — a single-threaded collector, simple and with low overhead, suitable for single-processor systems or small applications.
  • Parallel GC (Throughput Collector) — a multi-threaded collector focused on maximum throughput, well-suited for server applications with large amounts of available memory.
  • CMS (Concurrent Mark Sweep) — an older implementation that aims to minimize pauses through parallel work but can suffer from memory fragmentation.
  • G1 (Garbage First) — a modern collector that balances pauses and throughput, dividing the heap into regions and collecting the most "contaminated" areas first.
  • ZGC (Z Garbage Collector) — a low-pause collector that works with large heaps, minimizing pauses to milliseconds.
  • Shenandoah — similar to ZGC, low-pause, supported in OpenJDK.

Recommendations:

  • For most modern applications, G1 is recommended as it is well-balanced and supported by default from Java 9.
  • If minimal pauses and large heaps are important, consider ZGC or Shenandoah.
  • For simple or single-threaded applications, Serial GC.
  • Parallel GC is suitable if maximum throughput is important and pauses are not critical.

The choice depends on latency requirements, heap size, and load characteristics.