Skip to content

    System Design

    Garbage Collectors: G1 and ZGC, Pauses, Regions and GC Logs

    Learn how G1 uses regions and evacuation, how ZGC keeps pauses short, what GC logs show, and run a Java lab that reads both logs with no machine numbers.

    By Published 14 min read

    Share

    Standard lessonintermediateJava labBackend System Design

    Before this: The JVM Memory Model and Heap

    What you'll learn: By the end of this lesson you will be able to explain what a garbage collector must decide (what is live, where to move it, and when the application may be stopped), describe how G1 divides the heap into regions and collects young and old regions in turn, say what ZGC changes and what it costs, choose between the JDK's four collectors with the criteria its own guide gives, read the structure of a -Xlog:gc log for each, and run a Java lab that starts two child JVMs and prints only the structure of their logs.

    Think of a busy restaurant at closing time. One way to clear it is to send everyone out, clean everything, and open the doors again: simple, but diners wait at the door. Another is to clear a few tables at a time, choosing the messiest ones first, with short interruptions. A third is to clear around the diners with almost no interruption, at the price of extra staff and a slower kitchen. A garbage collector faces the same choice between how long the application stops, how much work the collector does, and how much memory it needs to breathe.

    The previous lesson showed what the heap is and that the collector reclaims objects no live thread can reach. This lesson is about how two of the JDK's collectors do that: G1, the default on most configurations, and ZGC, built for low latency.

    Verified with the Oracle HotSpot GC Tuning Guide for Java SE 25, the java command documentation and a lab run with Java 25, on 2026-11-16.

    The core idea

    A collector finds the objects that are still reachable, frees the rest, and usually moves survivors together to keep free memory usable. The collectors differ in how much of that work happens while application threads are stopped. G1 keeps pauses short by working on a few regions at a time and aiming at a pause-time goal. ZGC does "all expensive work concurrently", with pauses that its documentation says do not depend on heap size, and pays with some throughput.

    Three illustrations run through the lesson, each labelled:

    • Minimal example: the lab's two child JVMs and the structure of their logs.
    • Realistic example: ShopStream's checkout service and a latency spike, in "In practice".
    • Failure example: the "Full GC" fallback that G1 documents for when it runs out of memory while gathering liveness information.

    What every collector has to do

    The GC tuning guide describes a collector's job in two sentences: it determines which parts of memory are still in use and reclaims the unused memory for reuse. Its section on generations adds the observation that shapes every HotSpot collector, the weak generational hypothesis: "most objects survive for only a short period of time." So memory is managed in generations. "The vast majority of objects are allocated in a pool dedicated to young objects (the young generation), and most objects die there." When it fills, a minor collection collects only the young generation; when the old generation fills, a major collection collects the entire heap.

    Two terms recur. A pause is a time when application threads are stopped so the collector can work. Concurrent work runs while application threads continue. A collector's quality for a service is mostly the answer to "how long and how often are the pauses, and what does the concurrent work cost?" The guide's collector list gives the shape of each answer:

    Collector Flag What the guide says
    Serial -XX:+UseSerialGC "Uses a single thread to perform all garbage collection work"; suggested for small data sets (up to about 100 MB) or one processor with no pause-time requirements
    Parallel -XX:+UseParallelGC The throughput collector, a generational collector; for when peak performance is first and pauses of a second or longer are acceptable
    G1 -XX:+UseG1GC "A mostly concurrent collector"; for when response time matters more than throughput and pauses must stay shorter
    ZGC -XX:+UseZGC "Max pause times under a millisecond, but at the cost of some throughput"; for when response time is a high priority

    On which one you get without asking: the ergonomics page selects "the Garbage-First (G1) Collector on server-class machines, Serial Collector otherwise", where server-class means two or more processors and physical memory of at least 1792 MB (at the time of writing for Java 25). The java command page says of -XX:+UseG1GC: "By default, this option is enabled and G1 is used as the default garbage collector." The guide's advice is to first run your application and allow the VM to select a collector unless you have strict pause-time requirements.

    G1: regions, young collections, mixed collections

    G1 "partitions the heap into a set of equally sized heap regions, each a contiguous range of virtual memory". Regions play roles (eden, survivor, old) and the roles change as the program runs, so "young" and "old" are sets of regions, not two fixed areas.

    G1: one heap, many equal regions with changing rolesEden regions to Survivor regions (evacuate (copy)); Survivor regions to Old regions (age); Eden regions to Humongous (very large object)HEAP: REGIONS OF ONE EQUAL SIZEEden regions: new objectsEden regionsnew objectsSurvivor regions: survived onceSurvivorregionssurvived onceOld regions: long-livedOld regionslong-livedHumongous: half a region or moreHumongoushalf a region ormoreevacuate (copy)agevery large object

    Figure 1. G1's heap is a set of equally sized regions. How to read this: new objects start in eden regions; a collection copies survivors to survivor or old regions; an object at least half a region in size is a humongous object and gets its own treatment. The roles belong to regions, so the same region can be eden now and free later.

    Region size is chosen by the JVM. The guide says the default "is calculated to render roughly 2048 regions, with a maximum ergonomically determined value of 32 MB"; a size you set must be a power of 2. "Humongous objects are objects larger or equal the size of half a region." The lab prints these numbers for real runs below.

    G1 reclaims space "mostly by using evacuation: live objects found within selected memory areas to collect are copied into new memory areas, compacting them in the process." Copying live objects out of a region means every reference to them must be found; G1 keeps a remembered set per region of the locations outside it that point into it. Marking uses an algorithm called Snapshot-At-The-Beginning (SATB).

    The cycle has two phases (Figure 2). In the young-only phase, collections fill up the old generation gradually; a concurrent start collection begins marking in addition to a normal young collection, and concurrent marking determines which old regions contain live objects. In the space-reclamation phase, young collections also evacuate sets of old regions; these are called mixed collections. As a backup, "if the application runs out of memory while gathering liveness information, G1 performs an in-place stop-the-world full heap compaction (Full GC) like other collectors". The guide also says that if a collection frees no space at all, G1 schedules a Full GC.

    stateDiagram-v2 accTitle: The G1 collection cycle accDescr: G1 alternates between a young-only phase and a space-reclamation phase. A concurrent start collection begins marking, mixed collections reclaim old regions, and a full collection is the stop-the-world backup when memory runs out during marking. [*] --> YoungOnly YoungOnly --> YoungOnly: normal young collections YoungOnly --> Marking: concurrent start collection Marking --> SpaceReclamation: live old regions known SpaceReclamation --> YoungOnly: mixed collections done Marking --> FullGC: out of memory while marking FullGC --> YoungOnly

    Figure 2. How G1 moves between its phases. How to read this: the loop on the left is the normal life of a G1 JVM. The arrow to the Full GC state is the documented backup path, and the lab's logs show that short-lived garbage does not need it.

    The pause goal. The java command documents -XX:MaxGCPauseMillis as "a target for the maximum GC pause time... a soft goal", and for G1 the default is 200 milliseconds. The guide says G1 "tries to meet set pause-time targets with high probability over a longer time, but not always with absolute certainty for a given pause", and calls G1 "not a real-time collector".

    ZGC: concurrent, with pauses independent of heap size

    The guide's first sentence on ZGC is "The Z Garbage Collector (ZGC) is a scalable low latency garbage collector", and it says ZGC "performs all expensive work concurrently, without stopping the execution of application threads for more than a millisecond" and that "pause times are independent of the heap size that is being used". The java command page words the same claim more loosely, "max pause times of a few milliseconds", and notes the cost: "at some throughput cost". Treat both as documentation claims to verify against your own workload, not guarantees for it.

    Facts worth knowing, each from the guide:

    • As of JDK 24 ZGC is a generational collector, and the ZGenerational option has been removed. Articles from before that describe a non-generational ZGC.
    • The main tuning knob is the maximum heap size (-Xmx). -XX:SoftMaxHeapSize sets a soft limit; ZGC exceeds it only when needed to keep the application from stalling.
    • By default ZGC returns unused memory to the operating system (-XX:-ZUncommit disables it, and the uncommit delay is 300 seconds by default).
    • The guide says ZGC works well with heap sizes from a few hundred megabytes to 16 TB.

    What ZGC buys you is a latency profile that does not grow with the heap; what it costs is some throughput, and the guide's honest advice is that G1 is the better default when you have no strict pause-time requirement.

    Reading a GC log

    -Xlog:gc "logs messages tagged with the gc tag using info level to stdout" (the java command documentation); the older -Xloggc:file is replaced by -Xlog:gc:file. The lines look different per collector, which is why the lab asks for structure, not numbers. For G1, a young collection reads like Pause Young (Normal) (G1 Evacuation Pause) followed by heap before and after and the pause time; the word Pause marks a collection pause. For ZGC on Java 25 the lab's child JVM printed Minor Collection lines instead. Do not parse these lines for a pause statistic in production; read the cause in the brackets, compare heap after collections across time, and look for the word Full.

    Build it: read two GC logs without a single machine number

    This is the minimal example. GC times, sizes and counts differ from run to run and say nothing general, so the lab prints only the structure of each log.

    Goal. See which kinds of lines each collector writes for the same program, and see the G1 region size the JVM picks for different heap sizes.

    Setup. From the repository's examples/backend folder:

    ./gradlew :labs:gc-log-structure:check --console=plain
    ./gradlew -q :labs:gc-log-structure:run

    The first command runs 6 tests (three parse canned log lines, three start child JVMs). The second prints the table below. The code is in examples/backend/labs/gc-log-structure/src/main/java/buildingai/labs/gclogstructure/.

    How it works. GcLoad allocates 1 KiB byte arrays in a loop and keeps only the latest one, so a 64 MB heap forces many collections of almost entirely dead objects. ChildJvm starts a second JVM with -Xms64m -Xmx64m -Xlog:gc and one collector flag and returns its output. GcLogParser sorts lines into families (Using ..., Pause Young, Pause Full, Minor Collection, Major Collection), and the Demo prints yes or no per family. It also asks the JVM which G1 region size it picked for two heap sizes and one manual setting. It prints no pause time, no count and no heap size, and it does not compare collector speed.

    Expected output, captured from a real run (Java 25.0.3, 2026-11-08):

    Same program, 64 MB heap, -Xlog:gc. Only the structure of each log is printed, never a time, size or count.
    
    collector  banner (Using ...)             'Pause Young' lines      'Pause Full'   'Minor Collection' lines
    ----------------------------------------------------------------------------------------------------
    G1         G1                             yes                      no             no
    ZGC        The Z Garbage Collector        no                       no             yes
    
    G1 young pauses are labelled: Pause Young (Normal) (G1 Evacuation Pause): yes
    Every G1 young pause ended with no more heap in use than it started with: yes
    
    G1 region size picked by the JVM (documented: about 2048 regions, from 1 MB up to a 32 MB maximum, or set by hand):
      -Xmx64m                            region  1048576 bytes, humongous from   524288 bytes (half a region)
      -Xmx8g                             region  4194304 bytes, humongous from  2097152 bytes (half a region)
      -Xmx64m -XX:G1HeapRegionSize=2m    region  2097152 bytes, humongous from  1048576 bytes (half a region)

    What the output shows. G1's log has Pause Young lines and no Pause Full for this short-lived garbage, and the young pauses carry the cause label from the guide. ZGC's log at this level has no Pause Young lines and has Minor Collection lines instead. The region rows are the guide's rule at work: 64 MB divided into 2048 regions would be 32 KiB each, below the 1 MB smallest region the java command documents, so the JVM picked 1 MiB regions; 8 GB gives 4 MiB (8192 MiB over 2048); and the manual setting changes it to 2 MiB. A humongous object starts at half the region size in every row.

    Break it. In Demo.SMALL_HEAP, change -Xmx64m to -Xmx512m and run GcLoad by hand with -Xlog:gc. Expect fewer lines of the same kinds, and decide for yourself whether a count is structure.

    Stretch. Add a GcLoad mode that keeps 40 percent of what it allocates in a list and see which families G1 adds. Assert only what you can show appears.

    What the model leaves out. Pause times, throughput, memory footprint, any comparison of speed, and every collector flag beyond the one that selects the collector. The ZGC line wording may change between releases, which is why the tests assert families and not exact text.

    Choosing a collector: the trade-offs

    flowchart TD accTitle: Choosing a garbage collector accDescr: Start with the default collector. If the service has strict pause-time requirements and the default misses them in measurement, try ZGC. If the service is batch work where throughput matters more than pauses, consider Parallel. For a small data set or a single processor, Serial is suitable. A[Run on the default collector and measure] --> B{Does it meet the latency target?} B -->|yes| C[Keep it] B -->|no, strict pause targets| D[Try ZGC and measure again] B -->|no, work is batch and throughput matters| E[Try Parallel] A --> F{Tiny heap or one processor?} F -->|yes| G[Serial is suitable]

    Figure 3. A first-pass way to pick a collector. How to read this: the guide's own advice is to start with what the VM selects and move only when a measured requirement is missed. The branches follow its "Selecting a Collector" criteria.

    Option Gain Cost Wrong when
    G1 (default) Balanced; short pauses with a soft goal; little configuration Pauses still grow with the work per collection; not real-time A latency target is strict and measured as missed
    ZGC Pauses independent of heap size, per its documentation Some throughput; more concurrent work The service is throughput-bound batch work
    Parallel Highest throughput focus Longer pauses acceptable only Users wait on every request
    Serial Small, simple, no thread overhead Single thread Large heaps or many processors
    Tuning flags before measuring Feels productive Hides the real cause You have no GC log

    In practice: ShopStream's checkout latency spike

    This is the realistic example, an educational scenario on the course's running example ShopStream; nothing in it describes a real company. Every figure is illustrative.

    This is a realistic scenario, not a case history.

    The situation

    ShopStream's checkout service runs on the JVM. During a promotion, its slowest requests get much slower in bursts while the average stays flat. The team suspects garbage collection pauses but has never turned on a GC log.

    Starting architecture

    Checkout service: requests, JVM heap and GC logLoad balancer to Checkout JVM (requests); Checkout JVM to GC log file (collector lines); Checkout JVM to Latency dashboard (request latency)Load balancerLoad balancerCheckout JVM: G1, one heapCheckout JVMG1, one heapGC log file: -Xlog:gcGC log file-Xlog:gcLatency dashboardLatencydashboardrequestscollector linesrequest latency

    Figure 4. Put the GC log next to the latency graph. How to read this: the service sends request latency to the dashboard and collector lines to a file. The two are only useful together: a latency burst that lines up with a collection is a GC problem, one that does not is something else.

    Options considered

    Option What it does Risk
    A. Lower MaxGCPauseMillis first Asks G1 for shorter pauses Without a log you cannot see if pauses were the cause
    B. Switch to ZGC now Changes the latency profile Throughput cost; a change with no evidence
    C. Turn on -Xlog:gc on a canary, line it up with the latency graph, then decide Evidence first Takes a deploy and a promotion to observe

    The decision

    Option C. The team adds the log to one instance, keeps the default collector, and defines the question: do the slow requests coincide with Pause lines, and which cause labels appear in the brackets?

    Rollout and verification

    The canary runs through the next busy period. Verification is a comparison, not a statistic: the timestamps of the slowest requests against the timestamps of pauses, heap after collections over time, and whether any line mentions Full. If pauses explain the bursts, they try the next step (more heap headroom, or ZGC) on the canary only, with the same comparison.

    The 2 a.m. failure

    The page reads: checkout latency has spiked for several minutes and the instance failed its health check. The log shows a Pause Full line and heap after collection nearly equal to heap before. G1 fell back to the in-place stop-the-world compaction its guide describes as the backup when the application runs out of memory while gathering liveness information, because allocation outran the concurrent work and more data was live than expected.

    The checks: look at the lines before the Full collection for the cause label, compare live data after collections across the day, and look for a code path that keeps objects alive (the retained price tables of the previous lesson). The mitigation is to restart the instance and shed traffic while it recovers; the lasting fix is to find and bound what is being retained, size the maximum heap with headroom over the live data, and alert on heap after collection and on the appearance of any Full line.

    Architect's notes

    • Measure before tuning. The guide's own first step is to run on the default collector.
    • Alert on heap after collection, not on heap used: the second tells you about garbage, the first about live data.
    • A pause goal is a soft target, not a guarantee and not a free setting.
    • Check the version. ZGC became generational as of JDK 24; defaults are documented per release.
    • Keep the GC log on. It is a small file that makes a 2 a.m. page answerable.

    Common mistakes

    • Tuning flags without a GC log. You cannot see the effect.
    • Reading average latency and missing the pauses in the tail.
    • Assuming ZGC is "faster". Its documentation says some throughput cost.
    • Treating MaxGCPauseMillis as a guarantee. The documentation calls it a soft goal.
    • Comparing collectors from one laptop run and treating the result as general.
    • Copying flags from an article for an older JDK. Options and defaults move between releases.

    Key takeaways

    • A collector finds live objects, frees the rest and usually compacts; the collectors differ in how much of that stops the application.
    • G1 divides the heap into equal regions, evacuates survivors, uses a 200 ms soft pause goal by default and falls back to a Full GC when it runs out of memory during marking.
    • ZGC does its expensive work concurrently, documents pauses independent of heap size, and costs some throughput; as of JDK 24 it is generational.
    • Start with the default, turn on -Xlog:gc, read the structure and compare it with latency before changing anything.
    • Alert on heap after collection and on any Full collection.

    Practice exercises

    Exercise 1 (20 min). From the lab's table, explain each region size in terms of "about 2048 regions" and say when a 3 MB object would be humongous in each row.

    Exercise 2 (45 min). Run the lab. Run GcLoad by hand with -Xlog:gc and -XX:+UseG1GC, list the kinds of lines you see and say which are structure and which are measurements.

    Exercise 3 (1 hour). Run "Break it". Then run it with -XX:+UseZGC and describe in words how the log differs from G1's without quoting a number.

    Exercise 4 (2 hours). For ShopStream's checkout, search and image-processing services, say which collector you would start with, what you would measure and what result would make you change.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments