Serial, Parallel, G1 and ZGC at a glance
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)HotSpot ships several garbage collectors, and each one makes a different trade-off between short pauses, total speed and memory use. Picking one is a single flag on the java command, and the program's results never change: only when and how memory is freed does.
Serial and Parallel: one GC thread or many
The Serial collector does all garbage collection on one thread and stops the program while it works. It suits small heaps and machines with one CPU.
The Serial collector does all garbage collection work on one thread and stops your program while it works.
Example 1 · One program for every collector
import java.util.ArrayDeque;import java.util.Deque;
class Ticket { final String id; final String event; final int price;
Ticket(String id, String event, int price) { this.id = id; this.event = event; this.price = price; }}
public class FestTicketsDemo { public static void main(String[] args) { String[] events = {"Dance", "Music", "Hackathon", "Quiz"}; int[] prices = {150, 200, 300, 100}; Deque<Ticket> recent = new ArrayDeque<>(); // keeps only the last 1000 tickets long total = 0;
for (int i = 0; i < 3_000_000; i++) { int e = i % events.length; Ticket t = new Ticket("FEST-" + i, events[e], prices[e]); // short-lived object total += t.price; recent.addLast(t); if (recent.size() > 1000) { recent.removeFirst(); // the oldest ticket becomes garbage } }
System.out.println("Tickets sold: 3000000"); System.out.println("Total collected: Rs " + total); System.out.println("Last ticket: " + recent.peekLast().id); }}Tickets sold: 3000000 Total collected: Rs 562500000 Last ticket: FEST-2999999
What this code does
- The loop creates 3 million
Ticketobjects. Each one becomes garbage almost at once, because the deque keeps only the last 1000. - The output is the same with every collector. A collector changes when and how memory is freed, never what your program computes. The runs below all use this program.
Example 2 · Serial versus Parallel on the same program
javac FestTicketsDemo.javajava -XX:+UseSerialGC -Xmx256m -Xlog:gc FestTicketsDemojava -XX:+UseParallelGC -Xmx256m -Xlog:gc FestTicketsDemo[0.019s][info][gc] Using Serial [0.176s][info][gc] GC(0) Pause Young (Allocation Failure) 31M->0M(114M) 3.069ms [0.192s][info][gc] GC(1) Pause Young (Allocation Failure) 32M->0M(114M) 1.583ms [0.209s][info][gc] GC(2) Pause Young (Allocation Failure) 32M->0M(114M) 1.943ms ... [0.281s][info][gc] GC(6) Pause Young (Allocation Failure) 32M->0M(114M) 1.331ms Tickets sold: 3000000 Total collected: Rs 562500000 Last ticket: FEST-2999999 [0.021s][info][gc] Using Parallel [0.237s][info][gc] GC(0) Pause Young (Allocation Failure) 30M->0M(113M) 4.160ms [0.253s][info][gc] GC(1) Pause Young (Allocation Failure) 30M->0M(143M) 1.462ms [0.301s][info][gc] GC(2) Pause Young (Allocation Failure) 60M->0M(143M) 1.333ms [0.342s][info][gc] GC(3) Pause Young (Allocation Failure) 60M->0M(159M) 1.157ms Tickets sold: 3000000 Total collected: Rs 562500000 Last ticket: FEST-2999999
What this code does
- The first line of each run names the collector:
Using Serial, thenUsing Parallel. Every line after it is one stop-the-world young collection; "Allocation Failure" means the young generation was full. - Parallel grew its young generation and needed only 4 pauses here against Serial's 7. Your timings will differ: the numbers depend on the machine, the JDK build and what else is running. Lines marked
...were trimmed.
The Parallel collector does the same kind of work, but splits it across many GC threads, so each pause is shorter on a machine with several CPU cores. Both are generational: they collect the young generation often and the old generation rarely, and every collection is a stop-the-world pause. Parallel aims for throughput, which means the share of total time your program spends on its own work instead of on GC. On HotSpot (Java 17 and 21) its default goal, -XX:GCTimeRatio=99, means "spend at most about 1% of the time in GC". Serial suits small programs and machines with one CPU. Parallel suits batch jobs, such as a night job that builds fee reports, where only the total running time matters and nobody waits on a single request. Parallel was the default collector on server machines up to Java 8.
G1: the default collector since Java 9
G1 (Garbage-First) splits the heap into many equal-size regions and tries to keep each pause under a goal you set, 200 ms by default.
Example 3 · G1 by default, Serial on a one-CPU machine
java -Xmx256m -Xlog:gc FestTicketsDemojava -XX:ActiveProcessorCount=1 -Xmx256m -Xlog:gc FestTicketsDemo[0.019s][info][gc] Using G1 [0.219s][info][gc] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 23M->0M(118M) 21.118ms [0.244s][info][gc] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 38M->0M(118M) 2.114ms [0.283s][info][gc] GC(2) Pause Young (Normal) (G1 Evacuation Pause) 69M->0M(118M) 1.906ms [0.330s][info][gc] GC(3) Pause Young (Normal) (G1 Evacuation Pause) 69M->0M(118M) 1.785ms Tickets sold: 3000000 Total collected: Rs 562500000 Last ticket: FEST-2999999 [0.017s][info][gc] Using Serial [0.180s][info][gc] GC(0) Pause Young (Allocation Failure) 31M->0M(114M) 1.643ms [0.195s][info][gc] GC(1) Pause Young (Allocation Failure) 32M->0M(114M) 1.753ms ...
What this code does
- With no collector flag, this 12-core machine is server-class, so the JVM printed
Using G1. G1 names its pauses "Pause Young (Normal)" and gives the reason in the next brackets. -XX:ActiveProcessorCount=1makes the JVM believe it has one CPU. It is no longer server-class, so the JVM picked Serial on its own. The first G1 pause (21 ms) came while the JVM was still warming up; one short run is not a benchmark.
It is the default collector on HotSpot since Java 9 when the machine counts as a server-class machine: at least 2 CPUs and about 2 GB of memory (1792 MB). On a smaller machine, the JVM picks Serial instead. G1 is a balance. It does part of its old-generation work concurrently, which means beside your running program, so its pauses stay short and fairly predictable. In return it uses a little more CPU and memory than Parallel. For most web apps, such as a college ERP or an exam-results site, it is a good choice without any tuning.
ZGC: pauses well under a millisecond
ZGC is a collector that does almost all its work concurrently, including moving objects, so its pauses stay tiny, usually well below 1 ms on Java 17 and later, whether the heap is 1 GB or many terabytes.
Example 4 · ZGC: the pauses are hundredths of a millisecond
java -XX:+UseZGC -Xmx256m -Xlog:gc,gc+phases FestTicketsDemo[0.015s][info][gc] Using The Z Garbage Collector [0.144s][info][gc,phases] GC(0) Pause Mark Start 0.008ms [0.159s][info][gc,phases] GC(0) Concurrent Mark 15.232ms [0.159s][info][gc,phases] GC(0) Pause Mark End 0.024ms ... [0.169s][info][gc,phases] GC(0) Concurrent Select Relocation Set 9.323ms [0.169s][info][gc,phases] GC(0) Pause Relocate Start 0.019ms [0.171s][info][gc,phases] GC(0) Concurrent Relocate 1.113ms [0.171s][info][gc ] GC(0) Garbage Collection (Warmup) 32M(12%)->26M(10%) ... [0.265s][info][gc ] GC(1) Garbage Collection (Warmup) 110M(43%)->10M(4%) Tickets sold: 3000000 ...
What this code does
-Xlog:gc,gc+phasesalso prints each phase. The three "Pause" lines are the only times the program stopped: 0.008 ms, 0.024 ms and 0.019 ms. The "Concurrent" phases ran beside the program.- "Warmup" means ZGC is still learning how fast the program allocates, so it starts early cycles at fixed heap levels. The summary line shows heap used before and after, with the share of the maximum heap in brackets.
It arrived as an experimental feature in Java 11 and became production-ready in Java 15. You turn it on with -XX:+UseZGC. The price is extra CPU work and some extra memory, so total throughput can be a little lower than with G1 or Parallel. ZGC fits services where people wait for every response and the heap is large, such as a train-booking service that must answer quickly even during a 10 am Tatkal rush.
Java 21: generational ZGC
Generational ZGC is a version of ZGC that keeps separate young and old generations, so it can clean the many short-lived objects more often and more cheaply. In Java 21 you turn it on with -XX:+UseZGC -XX:+ZGenerational.
Example 5 · Generational ZGC on Java 21
java -XX:+UseZGC -XX:+ZGenerational -Xmx256m -Xlog:gc FestTicketsDemo[0.025s][info][gc] Using The Z Garbage Collector [0.255s][info][gc] GC(0) Major Collection (Warmup) [0.381s][info][gc] GC(0) Major Collection (Warmup) 26M(10%)->106M(41%) 0.126s [0.381s][info][gc] GC(1) Major Collection (Warmup) [0.507s][info][gc] GC(2) Minor Collection (Allocation Rate) Tickets sold: 3000000 [0.512s][info][gc] GC(2) Minor Collection (Allocation Rate) 162M(63%)->10M(4%) 0.005s [0.512s][info][gc] GC(1) Major Collection (Warmup) 108M(42%)->10M(4%) 0.132s Total collected: Rs 562500000 Last ticket: FEST-2999999
What this code does
- A "Minor Collection" cleans only the young generation; here it took 5 ms of mostly concurrent work and dropped the heap from 162 MB to 10 MB. A "Major Collection" cleans both generations.
- The first major collection ends higher (106M) than it started (26M) because the program kept allocating while ZGC worked beside it. That is normal for a concurrent collector. On Java 17 this command stops with "Unrecognized VM option 'ZGenerational'".
Plain -XX:+UseZGC on Java 21 still gives the older, single-generation ZGC. From Java 23, generational mode is the default, and Java 24 removed the single-generation mode, so there -XX:+ZGenerational only prints a warning and -XX:+UseZGC alone is enough. The flag is version-specific. Java 17 does not know ZGenerational and refuses to start with "Unrecognized VM option". From Java 23 the generational mode is the default for -XX:+UseZGC, and Java 24 removed the old mode, so there -XX:+UseZGC alone is enough.
Choosing and checking a collector
You choose a collector with one flag on the java command. Pass only one: two collector flags together stop the JVM with "Conflicting collector combinations in option list".
Example 6 · Ask the JVM which collector it uses
import java.lang.management.GarbageCollectorMXBean;import java.lang.management.ManagementFactory;import java.util.ArrayList;import java.util.List;
public class WhichCollectorDemo { public static void main(String[] args) { // Make some garbage so the collectors have work to count. List<String> marks = new ArrayList<>(); for (int i = 0; i < 2_000_000; i++) { marks.add("Roll-" + i + ": " + (i % 100)); if (marks.size() == 10_000) { marks.clear(); } }
System.out.println("Java " + Runtime.version().feature()); for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) { System.out.println(gc.getName() + " -> runs: " + gc.getCollectionCount()); } }}Java 21 G1 Young Generation -> runs: 2 G1 Concurrent GC -> runs: 0 G1 Old Generation -> runs: 0
What this code does
ManagementFactory.getGarbageCollectorMXBeans()lists the collector parts the JVM is running, with how many times each has run. The names tell you the collector:CopyandMarkSweepCompactmean Serial,PS ScavengeandPS MarkSweepmean Parallel,ZGC CyclesandZGC Pausesmean ZGC.- This run used G1 on Java 21, which also lists
G1 Concurrent GC; Java 17 shows only the young and old names. Your counts will differ from machine to machine.
-XX:+UseSerialGC: tiny heap or a single CPU, such as a small tool or a test container.-XX:+UseParallelGC: batch jobs where total time matters more than any single pause.-XX:+UseG1GC: the default and the right start for most services.-XX:+UseZGC: large heaps where every pause must stay tiny (add-XX:+ZGenerationalon Java 21).
To check which collector a program really uses, read the first line of a -Xlog:gc run ("Using G1"), or ask the JVM from inside the program, as in the example below.
Next step
Check your understanding
12 quick questions