Lesson · Garbage Collection & References
Garbage collectors: throughput, latency and footprint
15 min readCollectors
No collector wins throughput, latency and footprint at the same time. Choosing one is deciding which of the three you refuse to spend, and every default is that decision made on your behalf.
The triangle: three budgets, two losers
Every garbage collector is judged on three budgets, and they trade against each other. Throughput is how much CPU ends up doing application work rather than collection. Latency is the worst pause an application thread sees. Footprint is the extra memory and metadata the collector needs to do its job.
The three pull in different directions. A collector that never pauses must do its work concurrently, which costs throughput and memory for bookkeeping. A collector built for maximum throughput can afford long stop-the-world pauses. A collector with a tiny footprint cannot afford the machinery that would make pauses short. The triangle is a constraint, not a menu: you pick which corner to give up.
| Budget | How you feel it | Who gives it up |
|---|---|---|
| Throughput | the job finishes sooner; CPU spent collecting is CPU not spent on work | concurrent collectors, which do their work beside the application |
| Latency | the worst pause is short; no request stalls behind a collection | stop-the-world collectors, where a pause scales with the heap |
| Footprint | less memory for the same data; more of the container limit is yours | collectors with concurrent bookkeeping, colored pointers and spare space |
Pick the collector by the budget you refuse to spend: throughput, latency or memory. Ask for all three and you get a benchmark instead of an answer.
Collectors · the triangle and the region map
no collector wins all three axes
where each design leans
Positions show the trade each design leans into, not measured scores: Serial gives up throughput and latency for footprint, Parallel does the reverse, ZGC and Shenandoah buy sub-millisecond pauses with memory headroom, and G1 sits in the middle by design.
G1 · the same heap as regions
Region size is picked at startup (1 to 32 MB, typically so the heap holds about 2048 regions). An object at least half a region is humongous, gets contiguous regions in old, and the pair of H cells above is one object spanning two regions.
Stop-the-world families: Serial and Parallel
The oldest design is still shipped and still correct. Serial stops every application thread, collects with a single GC thread, and uses the least memory and the fewest moving parts. It is the right answer for small heaps, one-core containers and short-lived tools, where the pauses are milliseconds because there is not much heap to walk.
Parallel is the same stop-the-world design with a crew: several GC threads collect at once, which shortens pauses in wall-clock terms on multi-core machines and makes bytes collected per second the priority. It was the default through Java 8, and it is still the throughput-first choice for batch workloads.
One historical line before moving on: CMS, the first collector to chase low pauses by working concurrently, is gone. It was removed in Java 14, so any advice that begins with -XX:+UseConcMarkSweepGC is a museum piece.
| Collector | GC threads | Strength | Where it fits |
|---|---|---|---|
| Serial | one | smallest footprint, simplest pauses | small heaps, one core, tools |
| Parallel | many | best throughput, pauses with the whole crew | batch and analytics jobs |
A stop-the-world collector is not obsolete. When nothing user-facing waits for the pause, throughput is the only number that matters, and Parallel still wins it.
G1: regions, young and mixed collections
G1 has been the default since Java 9. It divides the heap into equal regions, sized from 1 to 32 MB so that the heap typically holds around 2048 of them, and gives each region a role: young, survivor or old. The generations from the heap-layout lesson still exist as sets of regions; the region is simply the unit the collector allocates, evacuates and reclaims.
G1 collects the young generation the way a generational collector always has, then occasionally runs a mixed collection that also evacuates the old regions holding the most garbage. The scheduling target is a pause budget: -XX:MaxGCPauseMillis, 200 by default, which G1 trades throughput and young-generation sizing against. It also marks the old generation concurrently, so a mixed collection only has to look at regions worth its time.
One object size gets special treatment. Anything at least half a region is humongous and is allocated in its own contiguous regions in old, because a huge array cannot be copied around cheaply. That is also why region size is worth understanding: an allocation that cannot find contiguous regions can force a collection that has nothing to do with your ordinary garbage.
A pause target is a goal, not a contract. G1 trades throughput and young-generation sizing to come close to MaxGCPauseMillis, and the log reports the misses.
ZGC and Shenandoah: concurrent marking and moving
ZGC and Shenandoah take the opposite bet: do almost everything while the application keeps running. Both mark and, crucially, relocate objects concurrently, so pauses stay in the range of root handling and do not scale with the size of the heap. ZGC became production-ready in Java 15 and supports heaps from 8 MB up to 16 TB; Shenandoah, developed by Red Hat and also production in Java 15, reaches the same goal with a concurrent compacting design of its own.
Moving objects while threads are running is the hard part, and ZGC pays for it with colored pointers and load barriers: references carry bits describing the relocation state, and the load barrier fixes a pointer the first time you use it. That bookkeeping is where the footprint goes. A collector that keeps the heap still during a pause does not need any of it.
A version note worth carrying: ZGC started as a single-generation collector and gained an experimental generational mode in Java 21, which later JDKs promote as the main mode while the original one is deprecated. Check the flags of the JDK you actually run rather than the blog post you remember.
Concurrent collectors move collection work beside your application, not out of it. The bill arrives as throughput and footprint, which is why the triangle still has three corners.
Choosing a collector for a real workload
Start from the budget, not from the collector. A nightly batch job whose pauses nobody can observe should not pay for sub-millisecond latency. A request-serving heap of tens of gigabytes should not accept a multi-second stop-the-world pause because the default was left unexamined on a machine much larger than the one it was tested on.
Then start from the default and change one thing at a time. G1 is the default because it is balanced across ordinary server workloads, and most services never need to leave it. The shapes that justify a deliberate choice are batch throughput, tight pause budgets, tiny containers and very large heaps. The board below maps one to the other.
The collector is chosen by the workload, not by taste. Write the budget down first; everything after that is measurement.
Collector board · workload in, collector out
pick a workloadworkload
Deep queues of work and nobody watching the pauses; wall-clock time is the only number that matters.
- Pauses are invisible when the only consumer is the next stage of the job.
- Multi-threaded stop-the-world collections use every core, which is what throughput wants.
- G1, the default, also works; Parallel remains the throughput-first choice.
What you give up: Long stop-the-world pauses. Fine for a batch, unacceptable behind a request.
the roster
One GC thread, stop the world, smallest footprint.
Many GC threads, stop the world, throughput first.
Region-based and generational, balanced against a pause target.
Concurrent marking and relocation, sub-millisecond pauses.
Concurrent compaction with low pauses, built by Red Hat.
Meter scores describe the trade each collector was designed around, not a benchmark: three filled bars across all three axes is the one result the triangle forbids.
The flags that matter
A short list covers almost every real deployment. Sizing first: -Xms and -Xmx set the initial and maximum heap, and a server that will grow to its maximum anyway should start there, because resizing the heap is work nobody asked for. -XX:+UseG1GC, -XX:+UseParallelGC, -XX:+UseZGC and -XX:+UseShenandoahGC pick a collector explicitly; leaving the default in place is also a decision, just an implicit one.
For G1, -XX:MaxGCPauseMillis is the target the collector schedules against, and -XX:G1HeapRegionSize fixes the region size when the automatic choice is wrong (humongous allocations are the usual reason). For all of them, -Xlog:gc* is the only honest witness: it reports every collection with its cause, the pause times and the space sizes the collector actually used.
// sizing + collector + pause target + the log, in one startup line: java -Xms2g -Xmx2g -XX:+UseG1GC -XX:MaxGCPauseMillis=50 \ -Xlog:gc*:file=gc.log:time,uptime:filecount=5,filesize=10M \ -jar app.jar
| Flag | What it does | When you reach for it |
|---|---|---|
| -Xms / -Xmx | initial and maximum heap size | servers: set both equal to avoid resize work |
| -XX:+UseParallelGC | multi-threaded stop-the-world collector | batch jobs where throughput is the only budget |
| -XX:+UseG1GC | regional generational default since 9 | ordinary services; the flag is usually redundant |
| -XX:MaxGCPauseMillis | G1 pause target, 200 by default | trading throughput for shorter pauses |
| -XX:+UseZGC | concurrent collector with sub-millisecond goals | large heaps and hard latency budgets |
| -Xlog:gc* | unified GC logging | always, before and after any change |
Tune with the log open or not at all. A flag change without -Xlog:gc* before and after is folklore with syntax.
Containers: the JVM already reads the limit
A modern JVM is container-aware by default: container support (on since Java 10, backported to 8u191) reads the cgroup memory limit, and the default maximum heap becomes a quarter of what the container may use. That is why a service that ran happily on a VM can be killed in a 512 MB container while the heap still looks small: the JVM sized itself from the limit, and metaspace, thread stacks and native buffers live outside the heap.
In containers, prefer percentages to fixed sizes. -XX:MaxRAMPercentage and -XX:InitialRAMPercentage express the heap as a fraction of the container limit, so the same image behaves correctly when the limit changes between environments. A hard -Xmx copied from a VM config is how images become environment-specific, and a container that ignores its limit is killed by the kernel rather than by OutOfMemoryError. The Diagnostics and Tooling lesson covers the tooling around all of this; the setting itself is this paragraph.
// container-aware sizing: fractions of the cgroup limit, not a number from a VM java -XX:InitialRAMPercentage=50 -XX:MaxRAMPercentage=75 -jar app.jar
Let the limit drive the heap, not a number from another machine. Percentages travel between environments; hardcoded heap sizes do not.
The collector playbook
When the collector becomes a decision rather than a default, work in this order:
- Write the budget first: worst acceptable pause, throughput you are willing to lose, memory you are willing to spend on bookkeeping.
- Start on the default (G1 on any modern JDK) and measure with -Xlog:gc* under realistic load, not a microbenchmark.
- If pauses miss the budget, lower the pause target before swapping collectors; if they still miss it on a large heap, that is the signal to move to ZGC or Shenandoah, which need memory headroom.
- If throughput is the budget (batch, analytics, offline indexing), compare against Parallel before accepting a latency-first collector.
- Change one flag at a time and keep the log from every run; a series of logs is the only defence against superstition.
The triangle is a constraint, not an opinion. Every collector you can name is a specific answer to which corner gets given up.
The default is a decision too
Two equally expensive mistakes live here: moving off the default because a blog post said so, and staying on it for a workload it was never balanced for (a latency-critical multi-gigabyte heap, a one-core sidecar). Someone made the default choice for you, based on general server workloads rather than yours. Write the budget down, read one GC log under real load, and only then change anything.
Interview angles
Which collector is the default, and since when?+
G1, since Java 9. Before that, Parallel was the default on server-class machines, and Serial on smaller ones.
The default is chosen for balance across ordinary server workloads. It is a good starting point and a poor ending point: a workload with a real pause budget or a real throughput goal needs the budget written down before any flag is touched.
Follow-up: When would you deliberately leave the default in place?
What does -XX:MaxGCPauseMillis actually promise?+
It is a target, not a guarantee. G1 adjusts young-generation sizing and trades throughput to approach the number, and it reports in the log when it misses.
The flag tells the collector what to optimise for, which is genuinely useful: without it G1 optimises for a default 200 ms. Treating the value as an SLA is the mistake; on a heap large enough, no stop-the-world collector can honour it.
Common misconception: That setting a lower pause target lowers the pauses directly, like a speed limit. It changes the schedule, and the cost lands on throughput.
Follow-up: What would you do if the target is consistently missed?
How does G1 organise the heap?+
Into equal-sized regions (1 to 32 MB, usually around 2048 of them) that take the roles young, survivor or old, reassigned between collections.
Young collections evacuate young regions; mixed collections add the old regions with the most garbage, which is how G1 keeps pauses bounded without collecting all of old. Objects half a region or larger are humongous and get their own contiguous regions in old.
Follow-up: Why does region size matter for large arrays?
When would you move to ZGC or Shenandoah?+
When the pause budget is tighter than a stop-the-world collector can honour, or the heap is large enough that pauses would scale with it. Both mark and relocate concurrently, with sub-millisecond goals.
The price is the footprint corner: concurrent relocation needs bookkeeping and headroom, so the heap has to be larger than the data. ZGC went production in Java 15 and started single-generation, gaining an experimental generational mode in Java 21; Shenandoah, from Red Hat, also went production in Java 15.
Common misconception: That a concurrent collector removes collection cost. It moves the cost off the pauses and into throughput and memory.
Why does container memory matter to JVM sizing?+
Because the JVM reads the cgroup limit and sizes the default heap as a quarter of it, so a fixed -Xmx from another machine is either wasteful or dangerous.
Container support is on by default since Java 10 (8u191 on 8). Percentages (-XX:MaxRAMPercentage, -XX:InitialRAMPercentage) express the heap as a fraction of the limit, which keeps one image correct across environments. Exceeding the limit gets the process OOM-killed by the kernel, which no heap dump explains.
Follow-up: What still lives outside the heap in a container?
Why is CMS not an option any more?+
It was removed in Java 14. The low-pause idea it introduced lives on in G1, ZGC and Shenandoah.
CMS marked concurrently but never compacted, so the old generation fragmented until a full collection fixed it. That failure mode is exactly what its successors solve with region-based or relocation-based designs.