Garbage Collection Explained: Mark-Sweep, Generational, G1, ZGC, Shenandoah and the Go GC Compared with Tuning Guidance (2026)

Garbage Collection Explained: Mark-Sweep, Generational, G1, ZGC, Shenandoah and the Go GC Compared with Tuning Guidance (2026)

Garbage Collection Explained: Mark-Sweep, Generational, G1, ZGC, Shenandoah and the Go GC Compared with Tuning Guidance (2026)

Most production “GC problems” are not collector problems at all. They are budgeting problems: a service is asked to deliver low pause times, high throughput and a small memory footprint at once, with too little heap headroom to pay for all three. Garbage collection algorithms differ mainly in how they convert spare memory into either CPU savings or shorter pauses. That matters more in 2026 than it did five years ago. Java 27 now picks G1 on every machine, Go 1.26 shipped the Green Tea collector by default, .NET enables DATAS out of the box, and CPython quietly rolled back its incremental collector. Meanwhile most of these runtimes now live inside containers with hard memory limits. This guide explains the mechanisms from first principles, compares the major collectors, and gives you the arithmetic to size heaps and tune pauses without guesswork.

What this covers: reachability and tracing, mark-sweep vs copying vs compaction, the tri-color invariant and barriers, generational collection, G1, ZGC, Shenandoah, the Go, .NET, CPython and V8 collectors, heap-sizing math, runnable tuning examples, and failure modes.

Context and Background

Automatic memory management has two jobs. It must hand out memory quickly, and it must reclaim memory that the program can no longer reach. The second job is the hard one, because “can no longer reach” has to be established while the program, called the mutator in GC literature, keeps running and rewriting pointers.

Two families dominate. Reference counting keeps a counter on every object and frees it when the count hits zero; CPython is the best-known production example. Tracing collectors start from a set of roots and follow pointers to find everything live, then reclaim the rest. Nearly every high-performance managed runtime today, including the JVM, Go, .NET and V8, is a tracing collector, often with reference counting nowhere in sight.

The incumbents in 2026 look like this. On the JVM, G1 has been the default on server-class machines since JDK 9 under JEP 248, and JEP 523 extends that to every environment in JDK 27. ZGC became production-ready in JDK 15 (JEP 377), gained generations in JDK 21 (JEP 439), and dropped its non-generational mode in JDK 24 (JEP 490). Shenandoah became a production feature in JDK 15 (JEP 379), and its generational mode became a product feature in JDK 25 (JEP 521). Go runs a concurrent, non-moving mark-sweep collector; Go 1.26 made the Green Tea marking design the default. .NET runs a generational, compacting collector with Workstation and Server modes, and DATAS on by default since .NET 9.

If you have read our coverage of the Go 1.27 release and its runtime changes or .NET 11’s cloud-native performance work, you have seen GC changes listed as bullet points. This post is the missing layer underneath: why those changes exist, and what they cost.

The thesis is simple and, in our experience, under-stated by most GC tutorials. Every collector is an exchange rate between heap headroom and either CPU or pause time. Headroom is the memory you allow above the live set. Tuning is mostly choosing that headroom deliberately and then picking the collector whose exchange rate fits your latency budget.

How Garbage Collection Algorithms Work: The Reference Model

A garbage collection algorithm identifies objects the program can no longer reach from its roots (stacks, registers and globals) and reclaims their memory. Tracing collectors mark everything reachable and then either sweep the rest into free lists, copy survivors elsewhere, or compact them in place. Concurrent collectors do this while the program runs, using barriers to stay correct.

Garbage collection algorithms reference model from roots through marking to sweep, copy or compact

Figure 1: The tracing pipeline shared by all major garbage collection algorithms, and the three ways to reclaim memory.

Figure 1 shows the pipeline every tracing collector implements. Roots seed a graph traversal; the traversal sets mark bits; the reclaim step then chooses one of three strategies. Sweeping builds free lists and leaves live objects where they are. Copying moves survivors into a fresh space. Compaction slides survivors together inside the existing space. The choice of reclaim strategy, more than anything else, determines fragmentation, allocation speed and how much spare memory the collector needs.

Reachability, not “unused”, is the contract

A collector cannot know whether your code will use an object again. It can only prove that no chain of pointers leads to it from a root. Roots are thread stacks, CPU registers, global or static variables, and runtime-internal handles such as JNI references. Anything reachable is conservatively treated as live, which is exactly why a forgotten entry in a static map is a “leak” in a garbage-collected language.

This also explains why GC cost scales with live data, not garbage. Marking visits every reachable object and pointer. Sweeping touches dead space but is cheap per byte. Copying touches only survivors. A heap with 200 MB live and 4 GB of garbage is cheap to collect with a copying collector; a heap with 4 GB live is expensive under any tracing scheme.

Three reclaim strategies and their real costs

Mark-sweep is the oldest strategy, dating to McCarthy’s Lisp work. After marking, the sweeper walks the heap and threads unmarked cells onto free lists. It needs no extra space and never moves objects, which makes it friendly to code that holds raw pointers. The price is fragmentation: after many cycles, free memory is scattered across holes that may not fit a large allocation. Allocation becomes a free-list search rather than a pointer bump. Go’s collector is a mark-sweep design, and it manages fragmentation with size-segregated spans instead of moving objects.

Copying (semi-space or evacuation) divides memory into regions. Survivors are copied out of a “from” region into a “to” region, and the from region is then free as a whole. Allocation is a simple pointer bump into contiguous free memory, which is as fast as allocation gets. The cost is that you need somewhere to copy into. A naive semi-space collector wastes half the heap. Region-based collectors like G1 and ZGC reduce that waste by evacuating only some regions per cycle. V8’s young-generation scavenger, described in the Orinoco write-up, is a classic semi-space copier.

Mark-compact slides live objects toward one end of a region and updates every pointer to them. It avoids fragmentation without reserving a copy space, but it needs extra passes to compute forwarding addresses and fix references. Historically, full-heap compaction was the source of the multi-second pauses that gave GC its reputation. Modern collectors compact incrementally, region by region, or concurrently.

The throughput, latency, footprint triangle

Every design decision above pushes on three costs. Throughput is the share of CPU the application gets rather than the collector. Latency is how long the application stalls, either in stop-the-world (STW) pauses or in allocation stalls. Footprint is the memory consumed beyond the live set.

You can usually optimise two at the expense of the third. Parallel stop-the-world collectors maximise throughput with modest footprint, but pause the world for the whole collection. Concurrent compacting collectors like ZGC minimise pauses but spend extra CPU on barriers and concurrent work, and want more headroom. A small, tightly packed heap minimises footprint but forces frequent collections. Recognising which corner you actually care about is the first tuning decision, and it is a business decision as much as a technical one.

Concurrency, the tri-color invariant and barriers

Stop-the-world collection is simple because the object graph is frozen. Concurrent collection is hard because the mutator keeps editing the graph during marking. The standard way to reason about this is Dijkstra’s tri-color abstraction. White objects have not been reached yet. Grey objects have been reached but their outgoing pointers have not been scanned. Black objects are reached and fully scanned. Marking ends when no grey objects remain, and every white object is garbage.

Tri-color concurrent marking with write barrier protecting the invariant in garbage collection algorithms

Figure 2: How a write barrier keeps concurrent marking correct when the mutator stores a pointer to a white object into a black one.

The danger, shown in Figure 2, is that the mutator stores a pointer to a white object into a black object and simultaneously deletes the last grey path to it. The collector never revisits the black object, so the white object is freed while still reachable. That is a use-after-free, the worst bug a GC can have. To prevent it, collectors enforce one of two invariants. The strong invariant says no black object may point to a white one; an insertion (Dijkstra-style) write barrier shades the new target grey. The weak invariant, used by snapshot-at-the-beginning (SATB) collectors, allows black-to-white pointers as long as some grey path remains; a deletion (Yuasa-style) barrier shades the old value being overwritten.

G1 uses SATB marking, which Oracle’s G1 documentation describes as taking “a virtual snapshot of the heap at the time of the Concurrent Start pause”. Objects that die during marking survive until the next cycle as floating garbage. That is the price of shorter Remark pauses. Go uses a hybrid write barrier that combines insertion and deletion shading so that goroutine stacks do not need re-scanning at the end of the cycle.

Moving collectors need a second kind of barrier. If ZGC relocates an object while a thread holds a reference, that thread must never see the stale address. ZGC solves this with load barriers and colored pointers: metadata bits in each 64-bit reference record its state, and a barrier on every reference load checks those bits and heals stale pointers. Shenandoah uses its own load reference barrier, which, per JEP 404, also supports compressed 32-bit object pointers. These barriers are the CPU tax you pay for pause times that do not grow with heap size.

Generational Garbage Collection and the Major Collectors in Depth

The weak generational hypothesis says most objects die young. Request buffers, iterators, temporary strings and boxed numbers typically live for microseconds. Generational garbage collection exploits this by allocating new objects in a small young space and collecting it often, while touching the large old space rarely. Since copying costs scale with survivors, and most young objects are dead, a young collection is cheap.

Generational garbage collection heap layout with young regions, old regions, humongous regions and remembered sets

Figure 3: A region-based generational heap. Card tables and remembered sets record old-to-young pointers so young collections need not scan the old generation.

The catch, illustrated in Figure 3, is old-to-young pointers. If an old object points to a young one, a young collection must treat that pointer as a root, or it will free a live young object. Scanning the whole old generation would defeat the purpose. So generational collectors use a write barrier to record such pointers. The classic structure is a card table: the heap is divided into small cards and the barrier dirties the card containing any updated reference field. G1’s documentation states its cards are 512-byte areas, and G1 keeps per-region remembered sets of card references. Generational ZGC, by contrast, records old-to-young field locations precisely in per-region bitmaps, one bit per potential field, according to JEP 439.

G1: region-based, pause-goal driven

G1 divides the heap into equal-sized regions. Oracle’s JDK 26 G1 documentation says the default region size is chosen to give roughly 2,048 regions, with an ergonomic maximum of 32 MB, and that user-specified sizes must be a power of two between 1 MB and 512 MB. Each region is dynamically labelled eden, survivor, old or humongous.

G1’s lifecycle has two phases. In the young-only phase, it runs young collections that evacuate eden and survivor regions. When old-generation occupancy crosses the Initiating Heap Occupancy threshold (default 45%, adapted at runtime), it starts concurrent marking. After Remark and Cleanup pauses, the space-reclamation phase runs mixed collections that evacuate young regions plus the old regions with the most garbage. That “garbage first” ordering gives the collector its name.

The headline control is -XX:MaxGCPauseMillis, which defaults to 200 ms. G1 sizes the young generation and picks how many old regions to include in each mixed collection so that pauses usually meet the goal. It is a goal, not a guarantee.

G1 also has a special case that causes many production incidents. Humongous objects are objects “larger or equal the size of half a region”, per Oracle’s docs. They are allocated directly into contiguous runs of regions. A 4 MB array on a heap with 2 MB regions consumes multiple whole regions, and the tail of the last one is wasted. Many such allocations fragment the heap and can force Full GCs.

Two recent changes matter. JEP 522 in JDK 26 added a second card table so application write barriers no longer need synchronisation with refinement threads. The JEP reports throughput gains “in the range of 5–15%” for applications that heavily modify reference fields, cuts the x64 barrier from about 50 instructions to 12, and adds about 2 MB of native memory per 1 GB of heap. JEP 523 in JDK 27, released on 15 September 2026, then removed the old rule that picked the Serial collector on machines with one CPU and under 1.8 GB of heap. G1 is now the default everywhere.

ZGC: concurrent everything, pauses decoupled from heap size

ZGC performs marking, relocation and reference processing concurrently. Its STW pauses only handle a small, bounded amount of root work. JEP 439 restates the design goals: pauses under 1 ms, heap sizes from a few hundred megabytes to many terabytes, and minimal manual tuning.

Generational ZGC splits the heap into young and old generations, collected independently. The JEP’s Apache Cassandra example reports the generational mode needing “a quarter of the heap size” while achieving four times the throughput of the non-generational mode, with sub-millisecond pauses. The non-generational mode was obsoleted by JEP 474 (generational by default in JDK 23) and removed by JEP 490 in JDK 24. On a current JDK, -XX:+UseZGC is simply generational ZGC.

The cost model is different from G1’s. ZGC pauses do not grow with heap or live-set size, but the collector needs headroom to keep up. If the application allocates faster than ZGC can reclaim, threads hit an allocation stall: they block until memory is freed. An allocation stall is effectively a pause, and it shows up in latency percentiles even though GC logs show tiny STW pauses.

Shenandoah: concurrent compaction with a load reference barrier

Shenandoah, contributed by Red Hat, also compacts concurrently. It entered OpenJDK as experimental in JDK 12 (JEP 189) and became a product feature in JDK 15 (JEP 379). Its generational mode arrived as experimental in JDK 24 (JEP 404) and became a product feature in JDK 25 (JEP 521). The default Shenandoah mode remains single-generation. You enable generations with -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational.

JEP 404 is candid about why generations were needed. It says non-generational Shenandoah delivers single-digit-millisecond pauses only within “limited operational envelopes” of heap occupancy and allocation rate. Generational mode aims to reduce sustained footprint and lower the risk of degenerated and full collections during allocation spikes. When Shenandoah cannot keep up, it falls back to a degenerated cycle that finishes the work under a pause, and as a last resort to a full GC.

The Go garbage collector: non-moving, pacer-driven

The Go garbage collector is a concurrent, tri-color, non-moving mark-sweep collector. The runtime documentation describes each cycle as STW sweep termination, concurrent mark and scan, and STW mark termination. Because it never moves objects, it needs no load barriers and no copy space. It relies on size-class spans to keep fragmentation manageable.

Go exposes two knobs, documented in the official Guide to the Go Garbage Collector. GOGC sets the heap target, with this exact formula:

Target heap memory = Live heap + (Live heap + GC roots) × GOGC / 100

GC roots have been included in that formula since Go 1.18. GOMEMLIMIT, added in Go 1.19, sets a soft limit on total runtime-managed memory. When the limit is near, the GC runs more often regardless of GOGC. To prevent a death spiral, the runtime caps GC CPU use at roughly 50% over a 2 × GOMAXPROCS CPU-second window. The guide is explicit about the consequence: the program “will slow down at most by 2x”, and it may exceed the memory limit rather than stop making progress.

Go 1.26 made Green Tea the default marking design. Instead of chasing pointers object by object, Green Tea queues whole spans and scans the objects that accumulated on each span together, improving memory locality. The Go 1.26 release notes say to expect “somewhere between a 10–40% reduction in garbage collection overhead in real-world programs that heavily use the garbage collector”. They also note a further gain of roughly 10% on newer amd64 CPUs that support vector instructions for scanning small objects. The opt-out is GOEXPERIMENT=nogreenteagc at build time, which the Go 1.26 notes said they expected to remove in Go 1.27. Go 1.27, released in August 2026, made no further GC-algorithm changes in its notes; it did add size-specialised small-object allocation routines and a GC-powered goroutine leak profile.

.NET, CPython and V8 in brief

The .NET GC is generational and compacting, with generations 0, 1 and 2. Microsoft’s documentation states the Large Object Heap holds objects of 85,000 bytes and larger, collected logically with generation 2. It offers Workstation GC for client apps and Server GC with per-core heaps for services. DATAS (Dynamic Adaptation To Application Sizes), opt-in in .NET 8 and default in .NET 9, is a Server GC variant that starts with one heap and grows or shrinks the heap count. Microsoft reports an over 80% working-set reduction for a 2–3% drop in maximum RPS on TechEmpower benchmarks on a 48-core Linux machine.

CPython combines reference counting with a cycle collector for reference cycles. The incremental cycle collector introduced in Python 3.14.0 was reverted in Python 3.14.5 (May 2026) after memory-pressure reports, restoring the three-generation collector from 3.13. The free-threaded build, officially supported from Python 3.14 under PEP 779, uses a single-generation, stop-the-world cycle collector, per PEP 703. Our Python 3.15 migration tutorial covers what else changed for ML pipelines.

V8’s Orinoco project moved JavaScript GC from sequential STW to mostly parallel and concurrent. It uses a semi-space scavenger for the young generation and mark-compact for the old one, plus idle-time GC scheduled by the embedder.

G1 vs ZGC vs Shenandoah vs Go: Comparison, Sizing Math and Tuning Walk-through

With the mechanisms in place, comparing garbage collection algorithms becomes concrete. The table below summarises the design choices that drive behaviour. It deliberately avoids benchmark numbers, because GC performance is workload-specific and published comparisons rarely transfer to your service.

Collector Generational Moves objects Main barrier STW pause scales with Typical failure mode
JVM Parallel Yes Yes, STW Card-marking write barrier Live young set, full heap on full GC Long full-GC pauses
JVM G1 Yes Yes, STW evacuation SATB + card-table write barriers Young and selected old regions Humongous fragmentation, evacuation failure, full GC
JVM ZGC Yes, since JDK 21 Yes, concurrent Load + store barriers, colored pointers Bounded root work, not heap size Allocation stalls
JVM Shenandoah Optional, product mode in JDK 25 Yes, concurrent Load reference barrier + SATB Bounded root work Degenerated cycles under pressure
Go GC No No Hybrid write barrier Mark termination, small Memory-limit thrash, high GC CPU
.NET GC Yes, gen 0/1/2 + LOH Yes, compacting Card-marking write barrier Ephemeral collections; background gen 2 LOH fragmentation, gen 2 pressure
CPython 3 generations for cycles No None, refcount ops on every store Cycle-collector pass Cycles and finalizers delay frees

A few rows deserve comment. “Moves objects” is the column that predicts fragmentation: non-moving collectors such as Go’s and CPython’s never compact, so long-running services with mixed object sizes can see heap growth that is not leaked memory. “STW pause scales with” predicts tail latency: only ZGC and Shenandoah decouple pauses from heap size. And “Main barrier” predicts the CPU tax that applies even when no GC is running.

A decision matrix for g1 vs zgc and friends

Choosing between garbage collection algorithms on the JVM usually reduces to g1 vs zgc. The question comes up in nearly every JVM platform review. The honest answer is that it depends on which corner of the triangle you are paying for. This matrix captures our working defaults. It is opinion built from the mechanisms above, not a vendor recommendation.

Workload profile First choice Why Revisit if
General web or API service, p99 budget of 50–200 ms G1 Default, balanced, good throughput after JEP 522 p99 GC pauses exceed budget
Latency-critical service, p99 budget under 10 ms Generational ZGC Pauses decoupled from heap size GC CPU or allocation stalls rise
Same, on a vendor build favouring it Generational Shenandoah Concurrent compaction, compressed oops friendly Degenerated cycles appear
Batch, ETL, offline analytics Parallel GC Maximum throughput, pauses irrelevant Job SLA becomes latency-bound
Tiny container, under 1 CPU, small heap G1 on JDK 27, else measure Serial JEP 523 says G1 now matches Serial closely Footprint is the binding limit
Go service in a fixed-size container GOGC default + GOMEMLIMIT Soft limit uses spare memory safely GC CPU climbs toward the 50% cap
.NET API on many cores, bursty traffic Server GC with DATAS Heap count adapts to load Throughput drop is unacceptable

Decision flow for gc pause time tuning across JVM, Go and .NET garbage collection algorithms

Figure 4: A decision flow for choosing a collector and the first tuning lever, by runtime and latency budget.

Figure 4 turns the matrix into a flow. Start with the runtime, then the latency budget, then the headroom you can afford. The flow ends at a first lever, not a final configuration. Every branch ends with “measure with GC logs”, because the only reliable tuning input is your own allocation profile.

Worked math: heap headroom, GC frequency and CPU overhead

The numbers in this subsection are illustrative, chosen to make the arithmetic visible. They are not measurements of any runtime. Substitute your own live-set size, allocation rate and marking throughput from GC logs.

Start with the definitions. Let L be the live set after a collection, H the heap size, and A the allocation rate in MB/s. Headroom is H − L. A tracing collector must run roughly once every (H − L) / A seconds, because that is how long it takes to fill the free space. Each cycle costs work proportional to L for marking, plus some per-cycle fixed overhead.

Example 1, Go service. Suppose L = 400 MB, GC roots are 20 MB, and GOGC = 100. The official formula gives a target of 400 + (400 + 20) × 100 / 100 = 820 MB. Headroom is 420 MB. At A = 500 MB/s, the GC cycles about every 0.84 seconds, or roughly 1.2 cycles per second.

Now assume, illustratively, that marking proceeds at 1 GB/s per core. Marking 400 MB then costs 0.4 core-seconds per cycle, so GC consumes about 0.48 cores on average. Double GOGC to 200: the target becomes 1,240 MB, headroom doubles to 840 MB, and the cycle rate halves to about 0.6 per second. GC CPU drops to roughly 0.24 cores. This is exactly the relationship the Go GC guide states: “doubling GOGC will double heap memory overheads and roughly halve GC CPU cost”.

Example 2, the same service in a 1 GiB container. With GOGC = 200, the 1,240 MB target would exceed the limit and the container would be OOM-killed under load. Set GOMEMLIMIT instead. The Go guide recommends leaving 5–10% headroom for memory the runtime does not know about, so a limit of about 920 MiB is reasonable. Now the GC behaves like GOGC = 200 when the live set is small and tightens automatically as the live set grows. If the live set ever approaches the limit, the 50% CPU cap kicks in. Your service slows down rather than crashing, which you will see as a latency regression, not an OOM.

Example 3, a concurrent JVM collector. Concurrent collectors need headroom for a different reason. While ZGC runs a cycle lasting T seconds, the application keeps allocating A × T megabytes. If A = 1 GB/s and a cycle takes 2 seconds, the heap needs at least 2 GB free when the cycle starts, beyond the live set, or threads will stall. Double the live set and the cycle takes longer, so the required headroom grows too. This is why “ZGC needs a bigger heap” is true in practice: it is buying pause-free operation with memory.

Example 4, container memory is not heap. A JVM in a 4 GiB pod with default settings gets a maximum heap of 25% of available memory, per OpenJDK’s long-standing default described in Red Hat’s container-tuning analysis. That is 1 GiB of heap and 3 GiB mostly idle. Raising -XX:MaxRAMPercentage is common, but the non-heap budget is real. Metaspace, code cache, thread stacks, direct buffers and GC data structures all live outside the heap. JEP 522 alone adds about 2 MB per GB of heap for the second card table. On .NET, Microsoft’s 2019 .NET blog explains that inside a memory-limited container the default GC heap hard limit is the greater of 20 MB or 75% of the container limit. If you want to understand how CPU limits interact with GC threads on Kubernetes, our deep-dive on CPU throttling, CFS quotas and cgroup v2 explains why concurrent GC threads can trigger throttling that looks like GC pauses.

Hands-on: Java flags and reading a GC log

Unified logging, available since JDK 9, is the single most useful GC tool on the JVM. Start every investigation by enabling it in production. The overhead of gc level info logging is low enough that most teams leave it on permanently.

# G1 with an explicit pause goal and fixed heap
java -XX:+UseG1GC \
     -Xms8g -Xmx8g \
     -XX:MaxGCPauseMillis=100 \
     -XX:+AlwaysPreTouch \
     -Xlog:gc*,gc+heap=debug:file=/var/log/app/gc.log:time,uptime,level,tags:filecount=10,filesize=50m \
     -jar app.jar

# Generational ZGC (the only ZGC mode on JDK 24 and later)
java -XX:+UseZGC -Xms16g -Xmx16g \
     -Xlog:gc*:file=/var/log/app/gc.log:time,uptime,level,tags \
     -jar app.jar

# Generational Shenandoah, a product option since JDK 25
java -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational \
     -Xlog:gc*:file=/var/log/app/gc.log:time,uptime,level,tags \
     -jar app.jar

# Container-aware sizing: heap as a share of the pod limit
java -XX:MaxRAMPercentage=60 -XX:+UseG1GC -jar app.jar

The log lines below are an illustrative sample in the shape G1 produces with -Xlog:gc. They are not from a real system, and exact wording varies between JDK versions.

[12.401s][info][gc] GC(41) Pause Young (Normal) (G1 Evacuation Pause) 3120M->1210M(8192M) 18.442ms
[13.977s][info][gc] GC(42) Pause Young (Concurrent Start) (G1 Humongous Allocation) 2650M->1302M(8192M) 21.003ms
[14.512s][info][gc] GC(43) Pause Remark 1410M->1398M(8192M) 4.880ms
[15.020s][info][gc] GC(43) Pause Cleanup 1402M->1402M(8192M) 0.311ms
[16.844s][info][gc] GC(44) Pause Young (Mixed) (G1 Evacuation Pause) 2980M->1105M(8192M) 32.176ms

Read each line left to right: uptime, GC number, pause type, cause, heap before, heap after, committed heap and pause duration. Three things to look for. First, the “after” number on young and mixed pauses approximates your live set plus survivors. That is your L for the math above. Second, a cause of G1 Humongous Allocation means large arrays are triggering cycles; check whether a larger -XX:G1HeapRegionSize would make them non-humongous. Third, any Pause Full line is a red flag that deserves a root-cause analysis, not a bigger heap.

Hands-on: Go gctrace

Go’s equivalent is GODEBUG=gctrace=1, which prints one line per collection to standard error. The format is documented in the runtime package.

GODEBUG=gctrace=1 GOMEMLIMIT=920MiB ./service 2> gctrace.log

# For pacer internals as well (verbose):
GODEBUG=gctrace=1,gcpacertrace=1 ./service
package main

import (
    "fmt"
    "runtime/debug"
    "runtime/metrics"
)

func main() {
    // Equivalent to GOGC=200 and GOMEMLIMIT=920MiB, set at runtime.
    debug.SetGCPercent(200)
    debug.SetMemoryLimit(920 << 20)

    samples := []metrics.Sample{
        {Name: "/gc/heap/goal:bytes"},
        {Name: "/gc/heap/live:bytes"},
        {Name: "/gc/cycles/total:gc-cycles"},
    }
    metrics.Read(samples)
    for _, s := range samples {
        fmt.Printf("%s = %d\n", s.Name, s.Value.Uint64())
    }
}

Here is an illustrative gctrace line, constructed to match the documented format rather than captured from a real service:

gc 214 @381.502s 3%: 0.041+5.8+0.052 ms clock, 0.33+1.2/11/24+0.41 ms cpu, 812->826->402 MB, 840 MB goal, 1 MB stacks, 0 MB globals, 8 P

The 3% is the share of time spent in GC since start. The three clock numbers are STW sweep termination, concurrent mark, and STW mark termination. The 812->826->402 MB triple is heap at start, heap at end, and live heap; the last number is your L. The 840 MB goal is the pacer’s target, which should match the GOGC formula unless the memory limit is binding. If the goal hugs your GOMEMLIMIT and the GC percentage keeps rising, you are approaching the CPU cap and need either more memory or a smaller live set.

Trade-offs, Gotchas, and What Goes Wrong

The failure modes of garbage collection algorithms are well understood, but they are easy to misdiagnose because the symptom is usually “latency got worse” rather than an error.

Allocation stalls hit concurrent collectors. ZGC and Shenandoah keep pauses tiny, but if allocation outruns reclamation, threads block waiting for memory. Your GC log reports sub-millisecond pauses while p99 latency spikes. The fix is more headroom, fewer allocations, or more concurrent GC threads, not a smaller pause goal.

Humongous objects hurt G1. Large byte arrays, such as serialisation buffers or image frames, land in dedicated regions, waste tail space and fragment the heap. The tell is G1 Humongous Allocation causes and a high humongous region count in gc+heap logs. Pool large buffers or raise the region size.

Promotion and evacuation failure. When a young collection cannot find space to copy survivors, G1 records an evacuation failure. Oracle’s docs warn that if a collection frees no space at all, G1 schedules a Full GC, an in-place compaction of the entire heap that “might be very slow”. Generational collectors on other runtimes fail similarly when the old generation fills faster than concurrent marking can clean it. Starting marking earlier, or growing the heap, is the usual remedy.

Memory-limit thrash is Go’s characteristic failure. If the live set grows close to GOMEMLIMIT, the collector runs nearly continuously until it hits the roughly 50% CPU cap. The service survives but at half speed. The Go guide explicitly advises against using the memory limit to avoid OOM when the program is already near its environment’s limit.

Finalizers and cleaners delay reclamation. Objects with finalizers need at least one extra cycle before their memory returns, and finalizer threads can fall behind. Java has deprecated finalization for removal; prefer try-with-resources and Cleaner. In CPython, objects in reference cycles wait for the cycle collector rather than freeing immediately.

Barrier tax. Concurrent collectors spend CPU on every pointer load or store, even between cycles. JEP 522’s reduction of G1’s barrier from about 50 to 12 instructions on x64 shows how large that tax can be.

Container mismatch. A heap sized for the host instead of the pod is still common. So is a heap that fills the pod limit, leaving nothing for native memory. Both produce OOM kills that look like GC failures. For the kernel side of this story, see our guide to Kubernetes memory QoS and pod-level resource managers.

Practical Recommendations

Treat tuning any of these garbage collection algorithms as capacity planning, not flag tweaking. The single most important number is your live set, and the second is your allocation rate. Get both from GC logs under realistic load before you change anything. Once you have them, the headroom math above tells you whether your heap is undersized, and the decision matrix tells you whether a different collector would buy you anything.

Prefer defaults first. On JDK 27, G1 is the default everywhere and has had significant throughput work. On Go 1.26 and later, Green Tea is the default and needs no flags. On .NET 9 and later, Server GC applications get DATAS automatically. Change collectors only when measured pauses, not intuition, violate an agreed budget.

Reduce allocation before tuning the collector. Fewer allocations mean fewer cycles under all garbage collection algorithms, so allocation profiling usually beats flag tuning. Pool large buffers, avoid boxing in hot paths, and watch for accidental retention in caches. If tail latency at the service level matters, combine GC data with queueing analysis; our piece on Little’s Law and tail-latency capacity planning shows how a short pause cascades into queue growth.

A short checklist:

  • Enable GC logging (-Xlog:gc*, GODEBUG=gctrace=1, or .NET GC event tracing) in production.
  • Measure live set L and allocation rate A under peak load.
  • Size heap headroom so cycles are not back-to-back; concurrent collectors need A × cycle time extra.
  • Set container-aware limits: MaxRAMPercentage on the JVM, GOMEMLIMIT at 90–95% of the pod limit on Go.
  • Pick the collector from the latency budget, then set one lever at a time.
  • Alert on Full GC, allocation stalls, degenerated cycles and GC CPU share above your threshold.

Frequently Asked Questions

What are the main types of garbage collection algorithms?

The main families are reference counting and tracing. Tracing collectors find live objects by following pointers from roots, then reclaim memory by mark-sweep (free lists, no moving), copying (evacuate survivors to fresh space) or mark-compact (slide survivors together). Production collectors combine these with generational layouts, parallelism and concurrency. For example, G1 is a generational, region-based copying collector; Go is a concurrent, non-moving mark-sweep collector; and CPython pairs reference counting with a generational cycle collector.

What is the difference between G1 and ZGC?

G1 is a region-based generational collector that evacuates objects during stop-the-world pauses and aims for a configurable pause goal, 200 ms by default. ZGC does marking and relocation concurrently using colored pointers and load barriers, so its pauses stay under a millisecond regardless of heap size. The trade-off is that ZGC spends more CPU on barriers and concurrent work and needs more headroom to avoid allocation stalls. G1 generally offers better throughput per core; ZGC offers better tail latency.

Which Java garbage collector is best for low latency?

For latency budgets under roughly 10 ms, generational ZGC is the usual first choice on current JDKs, because its pause times do not scale with heap or live-set size. Generational Shenandoah, a product feature since JDK 25, targets the same space with concurrent compaction. Both need extra heap headroom and CPU. If your budget is 50 ms or more, G1 with a tuned MaxGCPauseMillis is often sufficient and cheaper. Always validate with GC logs and end-to-end latency percentiles, not GC pause logs alone.

How does the Go garbage collector work?

The Go garbage collector is a concurrent, tri-color, non-moving mark-sweep collector. Each cycle has a short stop-the-world sweep termination, a concurrent mark and scan phase, and a short stop-the-world mark termination. A pacer starts cycles so the heap stays near a target set by GOGC, and GOMEMLIMIT adds a soft memory ceiling. Since Go 1.26, the default Green Tea design scans small objects span by span for better memory locality, reducing GC overhead in GC-heavy programs.

What is generational garbage collection?

Generational garbage collection splits the heap by object age because most objects die young. New objects go into a small young generation that is collected frequently and cheaply, since few objects survive. Survivors are promoted to an old generation collected less often. To avoid scanning the old generation during young collections, a write barrier records old-to-young pointers in a card table or remembered set. The JVM’s G1, ZGC and optional Shenandoah mode, .NET and V8 all use generational designs.

How do I reduce GC pause times?

First measure: enable GC logs and find which pause type dominates. For G1, lower MaxGCPauseMillis modestly, avoid fixed young-generation sizes, and eliminate humongous allocations. If pauses still exceed budget, move to generational ZGC or Shenandoah. In Go, pauses are usually short; latency problems more often come from GC CPU use, so raise GOGC or set GOMEMLIMIT to use spare memory. Across all runtimes, reducing the allocation rate shortens and spaces out GC work most reliably.

Further Reading

References

  1. OpenJDK, JEP 248: Make G1 the Default Garbage Collector. https://openjdk.org/jeps/248
  2. OpenJDK, JEP 377: ZGC, A Scalable Low-Latency Garbage Collector (Production), JDK 15. https://openjdk.org/jeps/377
  3. OpenJDK, JEP 379: Shenandoah, A Low-Pause-Time Garbage Collector (Production), JDK 15. https://openjdk.org/jeps/379
  4. OpenJDK, JEP 404: Generational Shenandoah (Experimental), JDK 24. https://openjdk.org/jeps/404
  5. OpenJDK, JEP 439: Generational ZGC, JDK 21. https://openjdk.org/jeps/439
  6. OpenJDK, JEP 474: ZGC Generational Mode by Default, JDK 23. https://openjdk.org/jeps/474
  7. OpenJDK, JEP 490: ZGC, Remove the Non-Generational Mode. https://openjdk.org/jeps/490
  8. OpenJDK, JEP 521: Generational Shenandoah, JDK 25. https://openjdk.org/jeps/521
  9. OpenJDK, JEP 522: G1 GC, Improve Throughput by Reducing Synchronization, JDK 26. https://openjdk.org/jeps/522
  10. OpenJDK, JEP 523: Make G1 the Default Garbage Collector in All Environments. https://openjdk.org/jeps/523
  11. Oracle, Java 27 release announcement, 15 September 2026. https://www.oracle.com/news/announcement/oracle-releases-java-27-2026-09-15/
  12. Oracle, JDK 26 GC Tuning Guide, Garbage-First (G1) Garbage Collector. https://docs.oracle.com/en/java/javase/26/gctuning/garbage-first-g1-garbage-collector1.html
  13. The Go Authors, A Guide to the Go Garbage Collector. https://go.dev/doc/gc-guide
  14. The Go Authors, Go 1.26 Release Notes. https://go.dev/doc/go1.26
  15. The Go Authors, Go 1.27 Release Notes. https://go.dev/doc/go1.27
  16. The Go Authors, runtime package documentation, GODEBUG gctrace. https://pkg.go.dev/runtime
  17. Microsoft, Fundamentals of garbage collection (.NET). https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals
  18. Microsoft, Dynamic adaptation to application sizes (DATAS). https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/datas
  19. Microsoft .NET Blog, Running with Server GC in a small container scenario, Part 1. https://devblogs.microsoft.com/dotnet/running-with-server-gc-in-a-small-container-scenario-part-1-hard-limit-for-the-gc-heap/
  20. Python, PEP 703: Making the Global Interpreter Lock Optional in CPython. https://peps.python.org/pep-0703/
  21. Python, PEP 779: Criteria for supported status for free-threaded Python. https://peps.python.org/pep-0779/
  22. Python, What’s New in Python 3.14, Garbage collection. https://docs.python.org/3.14/whatsnew/3.14.html#garbage-collection
  23. V8 team, Trash talk: the Orinoco garbage collector. https://v8.dev/blog/trash-talk
  24. Red Hat Developer, Overhauling memory tuning in OpenJDK containers. https://developers.redhat.com/articles/2023/02/20/overhauling-memory-tuning-openjdk-containers

By Riju — about

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *