Garbage collector (GC): the component responsable to manage the application heap, removing the unused objects.

Summary: Allocate memory to the application, detect memory not used anymore by the application, provides more memory to the application.

Simple steps: (1) Mark: identify pieces of memory are in use and not; (2) Sweep: Remove objects identified in the previous step.

JDK provides different garbage collection algorithms to be used the one that fit better with the application. The metrics to pay attention to the choice are:

  • Throughput: collection work per time unit
  • Latency: duration of a single operation
  • Memory footprint: extra memory necessary to GC operation


Serial

Focus: Footprint and startup time

  • Works with a single thread
  • Pause the application threads
  • Heap organized in generation
  • Not good to use in multi-thread applications. It is suitable for small, short-running applications
java -XX:+UseSerialGC -jar Application.java

Parallel

Focus: Throughput

  • Default for JDK 8 and earlier
  • Works with multiple thread
  • Copy the in-use memory to other locations in the heap
  • Can pause the application
  • Generational collector that maximizes garbage collection efficiency
// Numbers of threads
-XX:ParallelGCThreads=<N>
// Time of pause  
-XX:MaxGCPauseMillis=<N>.  
// Maximum throughput: 
-XX:GCTimeRatio=<N>  
// Maximum heap footprint
-Xmx<N>

// Enable
java -XX:+UseParallelGC -jar Application.java  

Garbage First (G1)

Focus: Balanced Performance between throughput and latency.

  • Default since JDK 9
  • Key technique: generational garbage collection
  • Partition heap with the same size
  • G1 splits the work in old-generation section into two phases: (1) identify live objects concurrently with the application, reducing the latency; (2) G1 incrementally reclaims memory from the old generation. Reclaiming the old generation incrementally reduce the pause times. it partitions the heap into a set of equal-sized heap regions The default value for the pause time is 200 ms
  • Similar to Parallel but avoid lengthy operations in the pauses
  • The work is concurrent of the application: decreases the times of the pauses but impact in the throughput.
  • Indicated to applications running on multi-processor machines with large memory space.
java -XX:+UseG1GC -jar Application.java

Z Garbage Collector (ZGC)

Focus: Latency

  • Since JDK 15
  • Impact in the throughput
  • Extremely small pauses
  • Partition the heap in different sizes
  • Colored pointers: uses some bits (metadata bits) of reference to mark the state of the object
  • Useful to application which require low latency or use a large heap
java -XX:+UnlockExperimentalVMOptions -XX:+UseZGC Application.java
// Numbers of threads
-XX:ConcGCThreads=<N>  

Shenandoah

Focus: Latency

  • Since JDK 12
  • Impact in the throughput
  • More CPU intensive
  • Small pauses
-XX:+UseShenandoahGC

ZGC vs Shenandoah


References