CodeGym /Courses /JAVA 25 SELF /Garbage collectors: G1, ZGC, Shenandoah, comparison

Garbage collectors: G1, ZGC, Shenandoah, comparison

JAVA 25 SELF
Level 64, Lesson 1
Available

1. Introduction to the garbage collector (GC)

If you have ever written in C or C++, you’ve surely faced the need to manually free memory using free() or delete. In Java it’s much simpler: you create an object with new, and you don’t need to delete it — a special “janitor” called the garbage collector (Garbage Collector, GC) does that for you.

The GC is part of the JVM that automatically frees memory occupied by objects that are no longer referenced. Thanks to it, Java developers don’t have to worry about forgetting to free memory (and causing a leak) or, conversely, accidentally deleting an object that’s still needed (and getting a crash).

But like any janitor, the GC isn’t perfect: sometimes it can intervene at the worst moment, doing a “deep clean” (Stop-the-World), or it might not work as fast as you’d like. That’s why the JVM has several different garbage collector implementations — and choosing the right one can noticeably affect application performance.

Main types of garbage collectors

Serial GC

  • Serial GC — the simplest and oldest garbage collector.
  • Works on a single thread.
  • Stops all other threads during collection (Stop-the-World).
  • Good for small applications without heavy multithreading.
  • Enabled with the flag: -XX:+UseSerialGC

Parallel GC

  • Parallel GC (also “Throughput Collector”).
  • Uses multiple threads for garbage collection.
  • Focused on maximum throughput.
  • Still performs collection with Stop-the-World pauses, but faster than Serial.
  • Suitable for server applications where small pauses are acceptable.
  • Enabled with the flag: -XX:+UseParallelGC

CMS (Concurrent Mark Sweep)

  • CMS — deprecated but long-popular GC that minimises pauses.
  • Works partially concurrently with the application, reducing stop time.
  • More complex to tune, has overhead.
  • Deprecated since Java 9 (deprecated).
  • Enabled with the flag: -XX:+UseConcMarkSweepGC

G1 (Garbage First)

  • G1 GC — modern default collector (since Java 9).
  • Balances minimal pauses and performance.
  • Splits the heap into many small regions (region-based model).
  • Can collect selectively by regions without touching the entire heap.
  • Allows setting a target maximum pause, for example -XX:MaxGCPauseMillis=200.
  • Enable flag: -XX:+UseG1GC (usually not needed, since G1 is the default).

ZGC and Shenandoah

  • ZGC and Shenandoah — modern low‑latency garbage collectors.
  • Goal — minimal pauses (milliseconds), even on huge heaps (up to terabytes).
  • Work almost entirely concurrently with the application.
  • Require Java 11+ (ZGC) or Java 12+ (Shenandoah).
  • Suitable for latency‑critical systems (exchanges, fintech, real‑time analytics).
  • Enable flags: -XX:+UseZGC or -XX:+UseShenandoahGC

3. How modern GCs work

Young and old generations (Young/Old Generation)

The JVM divides the heap into two large parts:

Young generation (Young Generation): all new objects go here. Collection happens often and quickly here (Minor GC).

Old generation (Old Generation, Tenured): objects that “survived” several collections in the young generation move here. Collection happens less often but takes longer (Major/Full GC).

Why is that? Most objects in Java live very briefly (for example, temporary strings, collections inside a method). Therefore, you can collect the young generation quickly and often without touching the old one.

Minor GC

  • Cleans only the young generation.
  • Fast, with a short pause.
  • Does not affect old objects.

Major (Full) GC

  • Cleans the entire heap (both young and old generations).
  • Can take a long time (seconds or more on large heaps).
  • Usually accompanied by a long application pause.

How does the GC determine which objects to delete?

The GC looks for “live” objects starting from root references (root set): local variables on thread stacks, static fields, method parameters, etc. Everything reachable is considered live. The rest is garbage.

4. Comparing modern collectors: G1, ZGC, Shenandoah

Let’s figure out how the most modern and popular GCs differ. Here’s a table:

Collector Primary goal Memory model Minimum pauses Scalability Support When to use
G1 Pause/throughput balance Regions ~10–200 ms Up to hundreds of GB Java 9+ (default) Most server applications
ZGC Minimal pause Regions, “colored pointers” <10 ms Up to terabytes Java 11+ Real-time, latency‑critical
Shenandoah Minimal pause Regions, “colored pointers” <10 ms Up to terabytes Java 12+ (Red Hat) Real-time, latency‑critical

G1 GC: Garbage First

  • Splits the heap into many regions (typically 1–32 MB each).
  • During collection, picks regions with the most garbage (“garbage first”).
  • Can collect only part of the heap instead of all at once.
  • Allows setting a target pause: -XX:MaxGCPauseMillis=200.
  • Suitable for balancing speed and pauses; used by default since Java 9.

Example of enabling it (if it’s disabled):

java -XX:+UseG1GC -jar myapp.jar

ZGC: Z Garbage Collector

  • Experimental in Java 11, stable since Java 15.
  • Barely pauses the application: pauses are usually <10 ms, even with 1–2 TB heaps.
  • Uses “colored pointers” (coloring) and special pointers.
  • Requires a 64‑bit JVM; does not work on 32‑bit systems.
  • Supported on Linux, macOS, Windows.

Enable example:

java -XX:+UseZGC -jar myapp.jar

Shenandoah

  • Developed by Red Hat; goals are similar to ZGC.
  • Minimal pauses, active concurrent work alongside the application.
  • Supports Linux and Windows; included in some OpenJDK builds.
  • Uses similar techniques but different internal algorithms.

Enable example:

java -XX:+UseShenandoahGC -jar myapp.jar

Visual comparison

graph TD
    A[Young generation] -->|Minor GC| B[Old generation]
    B -->|Major GC| C[GC Pause]
    D[G1: regions] --> E[Selective regions]
    F[ZGC/Shenandoah: regions] --> G[Concurrent collection]

5. Practice: how to find out and change the GC

How to find out which GC is used?

  1. JVM logs: Run the application with -Xlog:gc* (Java 9+) or -verbose:gc (before Java 8). The logs will show which GC is used and how often pauses occur.
  2. jcmd: Run:
    jcmd <pid> VM.flags
    
    where <pid> is the Java process ID.
  3. jvisualvm: In the “Monitoring” section, you can see the GC type.

How to change the GC for your application?

Add the required flag when launching the Java program:

G1 GC (default, you can specify it explicitly):

java -XX:+UseG1GC -jar myapp.jar

ZGC:

java -XX:+UseZGC -jar myapp.jar

Shenandoah:

java -XX:+UseShenandoahGC -jar myapp.jar

How to set heap size and pauses?

  • Maximum heap size: -Xmx2G
  • Minimum heap size: -Xms512M
  • For G1: desired pause — -XX:MaxGCPauseMillis=200

Full run example:

java -Xms512M -Xmx2G -XX:+UseG1GC -XX:MaxGCPauseMillis=100 -jar myapp.jar

6. Choosing a GC for different tasks

When to choose G1

  • In most server and desktop applications — an excellent default choice.
  • Works well on heaps from hundreds of megabytes to hundreds of gigabytes.
  • Balances speed and pauses.

When to choose ZGC or Shenandoah

  • If the application is sensitive to latency (latency‑critical: exchanges, online games, real‑time analytics).
  • If the heap is huge (hundreds of gigabytes and more).
  • If only minimal pauses (milliseconds) are acceptable.
  • Requires Java 11+ (ZGC) or Java 12+ (Shenandoah).

When Parallel GC is sufficient

  • For small applications where maximum throughput matters and pauses are acceptable.
  • For batch processing where you can “tolerate” a Full GC stop.

7. Example: comparing GC behavior on a simple application

A small application that generates many temporary objects (a simulation of order processing):

public class GCSimulator {
    public static void main(String[] args) {
        while (true) {
            // Create 100,000 objects each cycle
            for (int i = 0; i < 100_000; i++) {
                String s = new String("Order-" + i);
            }
            // A short sleep
            try { Thread.sleep(100); } catch (InterruptedException e) {}
        }
    }
}

Run it with different GCs and look at the logs:

java -Xmx256M -XX:+UseG1GC -Xlog:gc* GCSimulator
java -Xmx256M -XX:+UseZGC -Xlog:gc* GCSimulator

What will you see?
G1 will make frequent but short pauses. ZGC/Shenandoah — even shorter pauses, but they may occur more often. Parallel GC — longer pauses, but less frequent.

8. Common mistakes and nuances when working with GC

Mistake #1: Expecting the GC to solve all memory problems. GC is not a magic wand. If you keep references to unnecessary objects, no GC will help — you’ll get a memory leak.

Mistake #2: Forcing System.gc(). The JVM knows better when to collect garbage. Forcing GC can cause a long pause and reduce performance.

Mistake #3: Ignoring GC logs. If you don’t examine GC logs, you might miss that your application regularly “hangs” on a Full GC.

Mistake #4: Using outdated GCs. For example, CMS is no longer actively developed. It’s better to move to G1 or modern low‑latency collectors.

Mistake #5: Choosing the wrong GC for the job. If you have a latency‑critical application and you use Parallel GC — expect long pauses. If you have batch processing and you enable ZGC — you’ll get extra overhead.

1
Task
JAVA 25 SELF, level 64, lesson 1
Locked
Detecting the active garbage collector – JVM Detective 🕵️
Detecting the active garbage collector – JVM Detective 🕵️
1
Task
JAVA 25 SELF, level 64, lesson 1
Locked
Changing the Garbage Collector and Tuning Pause Time – Perfectionist Performance Tuning ⚙️
Changing the Garbage Collector and Tuning Pause Time – Perfectionist Performance Tuning ⚙️
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION