Types of Garbage Collectors

Before diving into the different types of garbage collectors, it’s important to understand some basic terms:

  • Stop-the-World Event: All application threads pause while the garbage collection (GC) process is running. Both minor and major GCs trigger this event.
  • JVM Memory Parameters:
    • -Xms: Sets the initial heap size.
    • -Xmx: Sets the maximum heap size.
    • -Xmn: Defines the size of the Young Generation.
    • -XX:PermSize: Sets the initial size of the Permanent Generation.
    • -XX:MaxPermSize: Sets the maximum size of the Permanent Generation.

1. Serial Garbage Collector (Serial GC)

Overview:

  • The Serial Garbage Collector is the most basic GC implementation in the JVM.
  • It is optimized for single-threaded environments and uses a single thread to perform all garbage collection tasks.
  • During GC, all application threads are paused, leading to a Stop-the-World (STW) event.

Behavior:

  • Executes minor and major collections in a fully sequential manner.
  • Stops the entire application during collection, regardless of heap size.
  • Does not take advantage of multi-core processors.

Performance Characteristics:

  • Suitable for small heaps and systems with limited CPU resources.
  • Predictable and low-overhead operation, but with longer pause times as heap size increases.
  • Not designed for throughput or low-latency environments.

JVM Argument:

-XX:+UseSerialGC

Recommended Use Cases:

  • Small or simple desktop applications.
  • Client-side applications where throughput and latency are not critical.
  • Embedded systems or devices with constrained hardware (e.g., single-core CPUs).
  • Testing or development environments where GC behavior should remain simple and easy to analyze.

Limitations:

  • Not suitable for modern server applications with high concurrency.
  • Poor scalability on multi-threaded or multi-core systems.
  • Increased pause times as memory demands grow.
GC Serial Type -  Types of Garbage Collectors
Figure 01: Serial GC

2. Parallel Garbage Collector (Parallel GC)

Overview:

  • Also known as the Throughput Collector, the Parallel GC is designed to maximize application throughput by utilizing multiple threads for garbage collection.
  • Like Serial GC, it causes Stop-the-World (STW) pauses, but performs collection tasks in parallel to reduce the overall pause duration.

Behavior:

  • Both minor and major GC operations use multiple threads to perform garbage collection tasks concurrently.
  • Despite its parallelism, all application threads are paused during GC, making it a Stop-the-World event.
  • Focuses on completing GC tasks as quickly as possible to return control to the application.

Performance Characteristics:

  • Optimized for multi-core processors.
  • Improves performance in applications with large heaps and high throughput requirements.
  • Less concerned with pause time minimization; instead, it prioritizes overall application performance and resource utilization.

JVM Argument: 

-XX:+UseParallelGC

Tuning Options:

  • -XX:ParallelGCThreads=<n>
    Specifies the number of threads used for parallel garbage collection.
    (n = number of GC threads)
  • -XX:MaxGCPauseMillis=<n>
    Sets a target for maximum pause time in milliseconds. The JVM attempts (but does not guarantee) to meet this target.
  • -XX:GCTimeRatio=<n>
    Sets the ratio of time spent on GC versus application execution. A lower value means more frequent collections but shorter pause durations.

Recommended Use Cases:

  • High-throughput applications such as batch processing, data analytics, or background task execution.
  • Scenarios where longer pause times are acceptable, but fast overall processing is a priority.
  • Applications running on multi-threaded, multi-core environments.
  • Systems where predictable low latency is not required, but consistent performance is.

Limitations:

  • Still introduces noticeable pause times due to Stop-the-World events.
  • Not ideal for latency-sensitive or real-time applications.
  • Requires tuning for optimal performance in large-scale deployments.
GC Parallel Type -  Types of Garbage Collectors
Figure 02: Parallel GC

3. Concurrent Mark Sweep (CMS) Garbage Collector

Overview:

  • The Concurrent Mark Sweep (CMS) garbage collector is designed to minimize application pause times by performing most of its work concurrently with the application threads.
  • It primarily targets the Old (Tenured) Generation and is often referred to as a low-latency collector.

Behavior:

  • Uses multiple threads to perform garbage collection phases concurrently with the application.
  • Still causes Stop-the-World (STW) pauses, but only during specific phases:
    • Initial marking of live objects.
    • Final remarking phase to capture changes made during concurrent marking.
  • If the heap changes significantly during concurrent collection, additional STW pauses may occur.

Performance Characteristics:

  • Reduces long pause times associated with major collections.
  • Utilizes more CPU resources due to concurrent background activity.
  • May introduce CPU contention, especially in systems with limited processing capacity.
  • CMS can lead to memory fragmentation, requiring occasional full compaction pauses (not automatic in CMS).

JVM Argument:

-XX:+UseConcMarkSweepGC

Tuning Options:

  • -XX:ParallelCMSThreads=<n>
    Sets the number of threads used by the CMS collector for concurrent phases.

Recommended Use Cases:

  • Applications where low pause times are critical, such as web servers, trading systems, or interactive applications.
  • Systems with spare CPU capacity that can accommodate the background GC activity.
  • Environments requiring predictable and short GC pauses, even if it means lower throughput.

Limitations:

  • Higher CPU usage due to concurrent processing.
  • Susceptible to heap fragmentation, which may eventually require a full GC that pauses all threads.
  • Deprecated in newer versions of the JVM (starting with Java 9), in favor of G1 GC and other modern collectors.
  • Requires careful tuning to avoid premature promotion failures and out-of-memory errors.
CMS Garbage Collector -  Types of Garbage Collectors
Figure 03: CMS Garbage Collector

4. G1 Garbage Collector (G1 GC)

Overview:

  • The G1 (Garbage First) Garbage Collector is a server-style collector introduced to provide both high throughput and low pause times.
  • Designed for multi-core processors and applications with large heap sizes (typically 4 GB or more).
  • Unlike traditional collectors, G1 divides the heap into a large number of equal-sized regions (instead of fixed-generation spaces), enabling more flexible and targeted memory management.

Behavior:

  • G1 performs garbage collection by identifying regions with the most garbage and collecting those first—hence the name “Garbage First.”
  • Uses parallel and concurrent threads to perform garbage collection with minimal application pauses.
  • Performs concurrent global marking to track live objects across the heap, reducing full GC frequency.
  • Supports both minor and mixed collections (young + old generation cleanup in one cycle).

Heap Structure:

  • The heap is broken into multiple regions, typically sized between 1 MB and 32 MB, depending on the total heap size.
  • Regions are categorized as:
    • Eden: For new object allocations.
    • Survivor: For recently promoted young objects.
    • Old (Tenured): For long-lived objects.
    • Humongous: For very large objects (larger than 50% of a region).
    • Available: Free memory regions.

Performance Characteristics:

  • Balances throughput and low pause times, making it ideal for modern, large-scale applications.
  • Avoids long full-GC pauses by performing background marking and selective region reclamation.
  • Better at handling fragmentation than CMS.
  • Suitable for applications requiring predictable, short pause times, even with large heaps.

JVM Argument:

-XX:+UseG1GC

Some important points related to G1GC

  • In G1, consecutive memory spaces are divided into fixed sizes named regions.
  • The basic region target value is divided into 2048 (2K) spaces. If 8G is the maximum size of Java Heap, the size of one region will be 4MB. (8192MB / 2048 = 4MB)
  • The region space can be adjusted from 1MB to 32MB with the -XX: G1RegionSize option, but it is not recommended that you directly tune.
  • GC operation for humongous regions is not optimized. Therefore, if the large object size is a problem in using G1 GC, it is a good idea to analyze the program to see why large objects are a problem. 
  • In Java 8, some improvements are done in the G1 garbage collector. Using -XX:+UseStringDeduplication JVM argument using along with the G1 garbage collector. This helps to remove duplicate string values to a single value in a single char[] array.

Key Tuning Options:

  • -XX:MaxGCPauseMillis=<n>
    Sets the target maximum pause time (in milliseconds). G1 tries to meet this soft goal.
  • -XX:G1HeapRegionSize=<n>
    Sets the size of each heap region (1 MB to 32 MB). Not commonly adjusted manually.
  • -XX:InitiatingHeapOccupancyPercent=<n>
    Sets the heap occupancy percentage at which a concurrent GC cycle is triggered (default: 45%).
  • -XX:G1MixedGCLiveThresholdPercent=<n>
    Regions with a higher percentage of live data than this value are excluded from mixed GCs (default: 65%).
  • -XX:G1HeapWastePercent=<n>
    Sets the acceptable amount of unused space (default: 10%).
  • -XX:+UseStringDeduplication
    Optional flag to remove duplicate string instances from memory, improving efficiency.

Recommended Use Cases:

  • Large, memory-intensive applications require short, consistent pause times.
  • Latency-sensitive server applications such as web services, messaging platforms, and online transaction systems.
  • Systems where predictable response time is more important than raw throughput.

Limitations:

  • Humongous objects (very large allocations) are not collected as efficiently and may cause fragmentation.
  • May require tuning to meet strict pause-time goals under high memory pressure.
  • Slightly more complex than CMS or Parallel GC in terms of internal behavior and configuration.

emory system.

GC G1 Type
Figure 04: G1 GC

5. Z Garbage Collector (ZGC)

Overview:

  • ZGC (Z Garbage Collector) is a scalable, low-latency GC introduced in JDK 11 and improved in later versions.
  • It is designed to maintain pause times below 10 milliseconds, even with very large heap sizes—up to multi-terabyte heaps.
  • ZGC performs most GC operations concurrently, minimizing disruption to application threads and ensuring consistently low pause times.

Behavior:

  • Performs concurrent phases for marking, relocating, and remapping memory, without stopping application threads for significant periods.
  • Uses colored pointers and load barriers to manage object relocation safely while the application is running.
  • Only minimal Stop-the-World events occur, and they last a few milliseconds, regardless of heap size.
  • Focuses on scalability, low latency, and heap size independence for pause times.

Heap Structure:

  • Heap is divided into dynamically-sized memory regions, categorized as:
    • Young: For short-lived objects.
    • Old: For long-lived objects.
    • Remapped: For objects that have been moved but are still being accessed.
  • ZGC does not use fixed generations (like Young or Tenured) in the traditional sense; it manages memory more flexibly.

Performance Characteristics:

  • Maintains sub-10ms pause times even for heaps in the gigabyte or terabyte range.
  • Minimizes application latency impact by performing nearly all work concurrently.
  • Scales efficiently across many CPU cores and very large heaps.
  • Eliminates the need for manual tuning in most cases—designed to be largely self-tuning.

JVM Argument:

-XX:+UseZGC

Key Tuning Options:

  • -Xmx<size>
    Heap size must be set explicitly; ZGC is designed to handle very large heaps.
  • -XX:SoftMaxHeapSize=<size>
    Provides a soft limit for the heap, allowing ZGC to try to stay within this bound while still having access to the full Xmx.
  • -XX:+UseLargePages
    Enables large memory pages for improved performance (especially on Linux systems).

Recommended Use Cases:

  • Latency-sensitive applications that require ultra-low GC pause times.
  • Large-scale, real-time systems such as trading platforms, ad servers, and large web services.
  • Applications running with large heaps (multiple gigabytes or terabytes).
  • Systems where predictable, short response times are critical, regardless of workload size.

Limitations:

  • Requires JDK 11 or later (more stable and feature-complete in JDK 15+).
  • Not supported on all platforms (initially limited to Linux/x64, now expanded to more OS and architectures).
  • Slightly higher memory overhead due to metadata like colored pointers and load barriers.
  • Not ideal for small applications where throughput is more important than pause time.

6. Shenandoah Garbage Collector

Overview:

  • Shenandoah GC is a low-pause time garbage collector developed by Red Hat and integrated into the OpenJDK.
  • It is designed to reduce GC pause times to a few milliseconds, even for large heaps (up to hundreds of gigabytes).
  • Achieves this by performing most GC operations concurrently with the application threads—including compaction, which traditionally causes long pauses in other GCs.

Behavior:

  • Shenandoah introduces concurrent compacting, meaning it can relocate live objects without stopping application threads.
  • Uses read and write barriers to safely move objects in the background while tracking references.
  • Only a few short Stop-the-World (STW) events occur during the collection cycle, typically during initialization and final update references.

Heap Structure:

  • Like G1 and ZGC, Shenandoah divides the heap into regions.
  • Regions are dynamically reused and resized, based on object allocation patterns.
  • It does not rely on generational collection (no separate young or old generations), though an optional generational mode is available in newer JDK versions (starting from JDK 17+).

Performance Characteristics:

  • Focused on ultra-low pause times, typically in the range of 1–10 ms.
  • Heap size has minimal effect on pause durations, making it ideal for large-memory applications.
  • Compaction and object movement happen concurrently, improving memory defragmentation without interrupting application execution.
  • Trades some CPU overhead for reduced pause time and smoother responsiveness.

JVM Argument:

-XX:+UseZGC

Key Tuning Options (optional):

  • -XX:ShenandoahGCHeuristics=<type>
    Controls GC behavior strategy. Options include:
    • normal: Balanced GC
    • aggressive: Frequent collection to reduce memory usage
    • compact: Emphasizes heap compaction
  • -XX:+ShenandoahUncommit
    Enables returning unused heap memory back to the OS.
  • -XX:MaxHeapSize=<size> or -Xmx<size>
    Explicitly sets the max heap size, especially useful for larger workloads.

Recommended Use Cases:

  • Interactive applications or real-time systems require consistently low pause times.
  • Large-scale applications running with heaps of tens or hundreds of GBs, such as in-memory databases, financial services, and microservices.
  • Workloads where pause-time consistency is more important than raw throughput.

Limitations:

  • Available only in OpenJDK 12+, with stable production readiness in JDK 17+.
  • Uses more CPU overhead due to concurrent marking, compacting, and use of memory barriers.
  • Less throughput-optimized compared to Parallel GC or G1 GC, making it a better fit for latency-sensitive workloads rather than CPU-bound batch jobs.
  • Still evolving; features and tuning options may differ across JDK versions.

Quick Comparison

Feature / GC TypeSerial GCParallel GCCMS GCG1 GCZGCShenandoah GC
Main GoalSimplicityHigh ThroughputLow Pause TimeBalanced (Low Pause + Throughput)Ultra-low Pause TimeUltra-low Pause Time
Pause TimesHighHighLowModerate to LowVery Low (<10ms)Very Low (<10ms)
ConcurrencyNoMinor GC onlyPartial (Old Gen only)Yes (Concurrent Mark + Mixed GC)Fully ConcurrentFully Concurrent (including compaction)
Heap Size SuitabilitySmallMedium to LargeMediumLargeVery Large (multi-TB)Very Large (100s of GBs)
ThroughputLowVery HighMediumHighMediumMedium
CPU UsageLowHighHigher (due to concurrent threads)Medium to HighHigher (concurrent background work)Higher (uses barriers + concurrent GC)
STW EventsFull GCFull GCInitial & Final MarkShort STW for marking & cleanupMinimal (a few ms)Minimal (a few ms)
CompactionYesYesNo (fragmentation risk)Partial (Mixed GC)Yes (Concurrent)Yes (Concurrent)
Generational SupportYesYesYesYes (via Regions)No (Region-based, but generational optional)No (optional in newer versions)
Tuning ComplexityVery LowModerateHighModerateVery Low (self-tuning)Moderate
JVM Argument-XX:+UseSerialGC-XX:+UseParallelGC-XX:+UseConcMarkSweepGC-XX:+UseG1GC-XX:+UseZGC-XX:+UseShenandoahGC
Java Version AvailabilityAll (legacy default)AllDeprecated (from JDK 9+)Default from JDK 9+JDK 11+ (better in JDK 15+)JDK 12+ (mature in JDK 17+)
Best Use CaseSmall apps, simple toolsBatch jobs, reporting, ETLLatency-sensitive apps with spare CPUGeneral-purpose large appsReal-time apps with huge heapsReal-time apps with consistent latency

Summary Recommendations:

  • Use Serial GC for simple, single-threaded desktop apps with small memory needs.
  • Use Parallel GC when raw throughput is more important than pause time (e.g., batch processing).
  • Use CMS GC in legacy systems needing low pause times but not ready for newer GCs (though it is deprecated).
  • Use G1 GC for a good balance of throughput and latency, especially on large heaps.
  • Use ZGC when very low pause times are critical and you have very large heaps (hundreds of GBs to TB).
  • Use Shenandoah GC if you need pause-time predictability and concurrent compaction for smooth performance.

You may be interested: