Sub topic 6
Choosing a collector: Serial, Parallel, G1, and ZGC
This chapter assumes you know the heap layout from the earlier chapters (eden, survivor spaces, old generation), the idea of reachability from GC roots, and the basic algorithms (mark-sweep, mark-compact, copying). It also assumes you can run java with command-line flags.
What a collector choice decides
HotSpot ships several garbage collectors. They all reclaim unreachable objects, but they differ in three measurable ways:
- Throughput is the share of total time the application spends running your code instead of collecting garbage.
- Pause time is how long all application threads stop while the collector works. These stops are called stop-the-world (STW) pauses.
- Footprint is the extra memory and CPU the collector needs for its own bookkeeping.
No collector wins on all three. Choosing one means deciding which of these your workload cares about most.
The four collectors
Serial
Serial uses one thread for all collection work. Young collections use copying. Old collections use mark-compact. Every collection is a full stop-the-world pause.
It has the smallest footprint and no thread coordination cost. It suits small heaps (tens to a few hundred MB), single-core containers, and short-lived command-line tools. Enable it with -XX:+UseSerialGC.
Parallel
Parallel uses the same generational design as Serial, but it runs collection with several threads. It is also called the throughput collector. Pauses are still fully stop-the-world, but multiple threads shorten them.
It suits batch jobs, offline processing, and any workload where total completion time matters more than the length of an individual pause. Enable it with -XX:+UseParallelGC. Control the thread count with -XX:ParallelGCThreads=N.
G1
G1 (Garbage-First) divides the heap into many equal-size regions, typically 1 MB to 32 MB each. Each region acts as eden, survivor, or old at a given moment, so the generations are logical sets of regions and not contiguous blocks.
G1 collects young regions with STW copying pauses. It also runs a concurrent marking cycle that finds which old regions hold the most garbage. It then collects those regions first, in mixed collections, which is where the name comes from. You give it a pause-time goal with -XX:MaxGCPauseMillis (default 200 ms), and it chooses how many regions to collect to try to meet that goal. The goal is a target, not a guarantee.
G1 has been the default collector since JDK 9, on machines that HotSpot classifies as "server-class" (at least 2 CPUs and about 1792 MB of memory). On smaller machines the JVM falls back to Serial.
ZGC
ZGC is designed for very low pause times. Pauses stay short (typically well under a millisecond in recent releases) and do not grow with heap size or live-set size. It achieves this by doing almost all work concurrently, including relocating objects while the application keeps running.
To move objects while threads are using them, ZGC uses colored pointers (metadata bits in the reference) and load barriers (small code snippets the JIT inserts at reference loads). When a thread loads a reference to an object that is being moved, the barrier fixes the reference on the spot. The cost is a modest throughput loss and extra CPU and memory use compared with Parallel.
ZGC was experimental in JDK 11 and became production-ready in JDK 15. Enable it with -XX:+UseZGC. Since JDK 21, the generational mode is available with -XX:+ZGenerational. In JDK 23 and later, generational mode is the default for ZGC. Check your JDK version, because older releases collect the whole heap in every cycle.
Comparison
| Collector | Flag | Threads during pause | Concurrent work | Best fit |
|---|---|---|---|---|
| Serial | `-XX:+UseSerialGC` | 1 | None | Small heaps, single core, tools |
| Parallel | `-XX:+UseParallelGC` | Many | None | Batch jobs, throughput first |
| G1 | `-XX:+UseG1GC` | Many | Marking, some refinement | General-purpose services |
| ZGC | `-XX:+UseZGC` | Very short | Marking, relocation | Large heaps, strict latency |
A test program
To compare collectors, you need a program that allocates a lot and keeps some data alive. This one fills a list with random-sized arrays, drops old entries, and reports elapsed time and total GC time using the standard management API.
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class GcCompare {
public static void main(String[] args) {
Random random = new Random(42);
List<byte[]> live = new ArrayList<>();
long start = System.nanoTime();
for (int i = 0; i < 2_000_000; i++) {
live.add(new byte[1024 + random.nextInt(4096)]);
if (live.size() > 20_000) {
live.subList(0, 10_000).clear(); // drop the oldest half
}
}
long elapsedMs = (System.nanoTime() - start) / 1_000_000;
long gcMs = 0;
long gcCount = 0;
for (GarbageCollectorMXBean bean : ManagementFactory.getGarbageCollectorMXBeans()) {
System.out.println(bean.getName() + ": count=" + bean.getCollectionCount()
+ ", time=" + bean.getCollectionTime() + " ms");
gcMs += Math.max(0, bean.getCollectionTime());
gcCount += Math.max(0, bean.getCollectionCount());
}
System.out.println("Elapsed: " + elapsedMs + " ms, GC total: " + gcMs
+ " ms over " + gcCount + " collections");
}
}Run it with each collector and the same heap size:
javac GcCompare.java
java -Xms1g -Xmx1g -XX:+UseSerialGC GcCompare
java -Xms1g -Xmx1g -XX:+UseParallelGC GcCompare
java -Xms1g -Xmx1g -XX:+UseG1GC GcCompare
java -Xms1g -Xmx1g -XX:+UseZGC GcCompareThe exact numbers depend on your hardware and JDK version, so do not copy numbers from other machines. Compare the trend. Parallel usually shows the lowest total GC time on this kind of batch work. ZGC reports many collections but with very short pauses, and its getCollectionTime can undercount concurrent work because that time is not paused time.
How to decide
Work through these questions in order.
- How much CPU and memory does the process get? With one core or under roughly 200 MB of heap, Serial is a reasonable choice. G1 and ZGC both need spare cores for their concurrent threads.
- Is this a batch or an interactive workload? If nobody waits on individual requests and you only care about when the job finishes, use Parallel.
- Is this a service where a pause of a few hundred milliseconds is acceptable? Use G1. It is the default for good reasons, and you often do not need to change anything.
- Do you have a strict latency target, such as a p99 of tens of milliseconds, or a heap of many GB or more? Test ZGC. Make sure the machine has CPU headroom.
Measure before switching. A collector change is a configuration change and easy to reverse, but conclusions drawn from a toy benchmark do not transfer to production traffic.
Gotchas and edge cases
- Defaults depend on the machine. The same JAR can run with G1 on a laptop and Serial in a one-CPU container. If behavior matters, set the collector explicitly. You can print the choice with
java -XX:+PrintFlagsFinal -version | grep Use.*GC. - Only one collector is active. Setting two
-XX:+Use...GCflags makes the JVM refuse to start with a conflicting-collector error. - Humongous objects in G1. An object larger than half a region is "humongous" and is allocated directly in contiguous old regions. Many large arrays can fragment the heap and trigger extra collections. Raise
-XX:G1HeapRegionSizeif this shows up in logs. - Full GC in G1 is a fallback. If concurrent marking cannot keep up with allocation, G1 falls back to a full STW collection. This is much slower than a normal pause, and frequent full GCs mean the heap is too small or the allocation rate is too high.
- ZGC allocation stalls. If the application allocates faster than ZGC can reclaim, threads stall until memory is free. The fix is usually more heap, which gives the concurrent cycle more room.
- ZGC and heap sizing. ZGC needs headroom beyond the live set because it frees memory only after relocation. Plan for a heap noticeably larger than the data you keep.
- Pause goals are not promises. An aggressive
-XX:MaxGCPauseMillison G1 makes it collect fewer regions per pause, which can raise overall GC frequency and lower throughput. - JDK version matters. Parallel was the default through JDK 8, G1 since JDK 9, and ZGC and G1 both improved a lot between JDK 11 and 21. Advice for one version may not apply to another.
Check which collector is running
This small program prints the active collectors by name, which helps when you inherit a launch script.
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
public class WhichGc {
public static void main(String[] args) {
for (GarbageCollectorMXBean bean : ManagementFactory.getGarbageCollectorMXBeans()) {
System.out.println(bean.getName());
}
}
}Typical output names are "Copy" and "MarkSweepCompact" for Serial, "PS Scavenge" and "PS MarkSweep" for Parallel, "G1 Young Generation" and "G1 Old Generation" for G1, and names starting with "ZGC" for ZGC.
Exercise
A payment service runs on 8 cores with a 24 GB heap. Users complain about occasional one-second freezes, and GC logs show G1 full collections. Which collector would you test next, and what would you check before and after the change?
Show answer
Test ZGC, because it targets pauses that do not grow with heap size, and the symptom is long stop-the-world pauses. Before the change, record pause times from -Xlog:gc* and the p99 request latency under realistic load. After the change, run the same load and compare pauses, p99 latency, CPU use, and memory use, since ZGC trades some throughput and needs extra heap headroom. Also check whether the heap is simply too small or the allocation rate too high, since either could cause the G1 full collections.
Exercise
A nightly job processes 200 GB of records on a 16-core machine. Nobody watches it, and it must finish as soon as possible. Which collector fits, and why?
Show answer
Parallel. Pause length does not matter for an unattended batch job, and Parallel uses all cores for stop-the-world collection with the least overhead, which maximizes throughput.