Skip to lesson

G1 cuts the heap into many equal regions and, in every pause, collects only as many of them as fit its pause time goal. It finds garbage in the old generation while your program runs, then cleans the old regions with the most garbage first, a few at a time.

The heap as equal-size regions

G1 is Java's default garbage collector: it splits the heap into many regions and collects the regions with the most garbage first, aiming for short pauses.

A region is one of the equal-size blocks G1 cuts the heap into. Each region has one job at a time: eden, survivor, old, humongous or free.

The G1 heap as a grid of equal regions. Each region is eden (E), survivor (S), old (O), part of a humongous object (joined H) or free. A generation is just the regions with that role. G1 collects as many regions as fit the pause goal, -XX:MaxGCPauseMillis=200 by default.

Example 1 · See the region size the JVM chose

Terminal
java -Xlog:gc+init -versionjava -Xmx8g -XX:+PrintFlagsFinal -version | grep G1HeapRegionSize
Sample output
[0.017s][info][gc,init] CardTable entry size: 512
[0.021s][info][gc,init] Version: 21.0.7+9-b895.130 (release)
[0.021s][info][gc,init] CPUs: 12 total, 12 available
[0.021s][info][gc,init] Memory: 7521M
...
[0.021s][info][gc,init] Heap Region Size: 1M
[0.021s][info][gc,init] Heap Min Capacity: 8M
[0.021s][info][gc,init] Heap Initial Capacity: 118M
[0.021s][info][gc,init] Heap Max Capacity: 1882M
...
[0.021s][info][gc,init] Parallel Workers: 10
[0.021s][info][gc,init] Concurrent Workers: 3
...
openjdk version "21.0.7" 2025-04-15
...

   size_t G1HeapRegionSize                         = 4194304                                   {product} {ergonomic}

What this code does

  • -Xlog:gc+init prints G1's start-up settings. On this 7.5 GB machine the default maximum heap is 1882 MB, so G1 chose 1 MB regions. Your memory and region size may differ.
  • With -Xmx8g the same JVM picks 4 MB regions: 8 GB divided by 2048 is 4 MB. -XX:+PrintFlagsFinal prints every flag with its final value; on Windows Command Prompt use findstr G1HeapRegionSize instead of grep.

So in G1 the young and old generations are not two fixed areas; they are just sets of regions, and a region can be eden now and old later. The JVM picks the region size at start-up: a power of two between 1 MB and 32 MB, so that the heap has about 2048 regions. A 2 GB heap gets 1 MB regions, an 8 GB heap 4 MB regions. You can set it yourself with -XX:G1HeapRegionSize=4m, but you rarely need to. An object of at least half a region is humongous: G1 puts it straight into one or more free regions of its own, never in eden. Many large arrays, such as big report buffers, can therefore fill the heap faster than you expect.

The pause time goal: -XX:MaxGCPauseMillis

-XX:MaxGCPauseMillis is the pause time G1 tries to stay under. The default is 200 ms on HotSpot (Java 17 and 21). It is a goal, not a promise: G1 may miss it when the heap is nearly full.

Example 2 · A lower pause goal keeps eden small

Terminal
java -Xms1g -Xmx1g -Xlog:gc,gc+heap FestTicketsDemojava -Xms1g -Xmx1g -XX:MaxGCPauseMillis=2 -Xlog:gc,gc+heap FestTicketsDemo
Sample output
[0.017s][info][gc] Using G1
[0.242s][info][gc,heap] GC(0) Eden regions: 51->0(65)
...
[0.242s][info][gc     ] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 51M->0M(1024M) 14.472ms
[0.295s][info][gc,heap] GC(1) Eden regions: 65->0(613)
...
[0.295s][info][gc     ] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 65M->0M(1024M) 2.101ms
Tickets sold: 3000000
...

[0.019s][info][gc] Using G1
[0.316s][info][gc,heap] GC(0) Eden regions: 51->0(50)
...
[0.340s][info][gc,heap] GC(1) Eden regions: 50->0(50)
...
[0.372s][info][gc,heap] GC(2) Eden regions: 50->0(50)
...
[0.425s][info][gc,heap] GC(3) Eden regions: 50->0(50)
...
[0.425s][info][gc     ] GC(3) Pause Young (Normal) (G1 Evacuation Pause) 50M->0M(1024M) 1.740ms
Tickets sold: 3000000
...

What this code does

  • "Eden regions: 65->0(613)" means 65 eden regions before the pause, 0 after, and a target of 613 for the next cycle. With the 200 ms default and short pauses, G1 grew eden a lot.
  • With -XX:MaxGCPauseMillis=2, G1 kept eden at 50 regions, about 5% of the 1024 MB heap, and needed 4 young pauses instead of 2. Lines marked ... were trimmed; timings differ on your machine.

G1 meets the goal mainly by choosing how many regions to collect in one pause. A young collection must copy every live object out of eden, so a smaller eden means a shorter pause. After each pause G1 measures how long the copying took and sets the eden size for the next cycle. A lower goal is not free. Smaller eden means more frequent collections, more total GC work and lower throughput. G1 also will not shrink the young generation below about 5% of the heap, so a goal that is too low simply cannot be met.

Change the goal only after GC logs show pauses that are too long for your users, and measure again after the change.

Young and mixed collections

A young collection in G1 copies the live objects out of all eden and survivor regions, into survivor regions or, for older objects, into old regions. The emptied regions become free at once. The log calls it "Pause Young (Normal)".

Example 3 · Results pages that live long, then die

ResultsCacheDemo.javaJava
import java.util.HashMap;import java.util.Map;
public class ResultsCacheDemo {    static Map<Integer, byte[]> resultPages = new HashMap<>();
    public static void main(String[] args) {        // Phase 1: cache 400 result pages of 100 KB each (about 40 MB).        for (int roll = 0; roll < 400; roll++) {            resultPages.put(roll, new byte[100 * 1024]);            makeShortLivedGarbage(2_000);        }        System.out.println("Cached pages: " + resultPages.size());
        // Phase 2: results of the first 300 rolls are withdrawn; their pages become garbage.        for (int roll = 0; roll < 300; roll++) {            resultPages.remove(roll);        }        System.out.println("Pages after withdrawal: " + resultPages.size());
        // Phase 3: normal traffic keeps creating short-lived objects.        long checksum = 0;        for (int request = 0; request < 2_000; request++) {            checksum += makeShortLivedGarbage(2_000);        }        System.out.println("Requests served: 2000, checksum " + checksum);    }
    static long makeShortLivedGarbage(int count) {        long sum = 0;        for (int i = 0; i < count; i++) {            String line = "Roll " + i + " scored " + (i % 100);            sum += line.length();        }        return sum;    }}
Output
Cached pages: 400
Pages after withdrawal: 100
Requests served: 2000, checksum 73380000

What this code does

  • Phase 1 keeps 400 result pages of 100 KB each, about 40 MB, so they survive young collections and move to old regions.
  • Phase 2 withdraws 300 results, which makes most of those old regions garbage. Phase 3 keeps creating short-lived strings, so young collections keep happening. Run it below with -Xlog:gc.

Example 4 · Young, concurrent start and mixed collections in one log

Terminal
java -Xmx64m -Xlog:gc ResultsCacheDemo
Sample output
[0.015s][info][gc] Using G1
[0.162s][info][gc] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 23M->10M(64M) 8.953ms
[0.191s][info][gc] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 26M->17M(64M) 5.186ms
[0.206s][info][gc] GC(2) Pause Young (Normal) (G1 Evacuation Pause) 33M->26M(64M) 5.926ms
[0.216s][info][gc] GC(3) Pause Young (Normal) (G1 Evacuation Pause) 39M->33M(64M) 5.449ms
[0.224s][info][gc] GC(4) Pause Young (Concurrent Start) (G1 Evacuation Pause) 45M->40M(64M) 4.321ms
[0.224s][info][gc] GC(5) Concurrent Mark Cycle
[0.227s][info][gc] GC(5) Pause Remark 41M->41M(64M) 0.524ms
[0.228s][info][gc] GC(5) Pause Cleanup 41M->41M(64M) 0.065ms
[0.228s][info][gc] GC(5) Concurrent Mark Cycle 3.493ms
Cached pages: 400
Pages after withdrawal: 100
[0.238s][info][gc] GC(6) Pause Young (Normal) (G1 Evacuation Pause) 49M->40M(64M) 1.361ms
[0.244s][info][gc] GC(7) Pause Young (Concurrent Start) (G1 Evacuation Pause) 50M->40M(64M) 0.859ms
[0.244s][info][gc] GC(8) Concurrent Mark Cycle
[0.246s][info][gc] GC(8) Pause Remark 43M->21M(64M) 0.698ms
[0.247s][info][gc] GC(8) Pause Cleanup 22M->22M(64M) 0.081ms
[0.247s][info][gc] GC(8) Concurrent Mark Cycle 3.233ms
[0.252s][info][gc] GC(9) Pause Young (Prepare Mixed) (G1 Evacuation Pause) 29M->18M(64M) 0.972ms
[0.267s][info][gc] GC(10) Pause Young (Mixed) (G1 Evacuation Pause) 43M->13M(64M) 1.211ms
[0.288s][info][gc] GC(11) Pause Young (Normal) (G1 Evacuation Pause) 49M->13M(64M) 0.782ms
[0.309s][info][gc] GC(12) Pause Young (Normal) (G1 Evacuation Pause) 50M->13M(64M) 0.816ms
Requests served: 2000, checksum 73380000

What this code does

  • GC(0) to GC(3) are normal young pauses, and the heap after each one grows (10M, 17M, 26M, 33M) because the cached pages move to old regions. At GC(4) the old regions filled enough of the heap, so G1 started a marking cycle.
  • At GC(8) Remark the heap dropped from 43 MB to 21 MB: old regions holding only withdrawn pages were completely empty. GC(9) prepared the mixed phase and the mixed collection GC(10) cleaned more old regions, bringing the heap to 13 MB.

A mixed collection does the same young work, and in the same pause also cleans a few old regions that marking found full of garbage. The log calls it "Pause Young (Mixed)". Old regions are cleaned only this way, a few per pause, so the old generation never needs one long pause in normal running.

Concurrent marking of the old generation

Concurrent marking is how G1 finds live objects in the old generation while your program keeps running. It starts when old regions fill a set share of the heap, 45% at first (-XX:InitiatingHeapOccupancyPercent).

Example 5 · Inside one marking cycle with -Xlog:gc*

Terminal
java -Xmx64m "-Xlog:gc*" ResultsCacheDemo
Sample output
...
[0.247s][info][gc,heap     ] GC(7) Old regions: 41->41
...
[0.247s][info][gc          ] GC(7) Pause Young (Concurrent Start) (G1 Evacuation Pause) 50M->40M(64M) 1.310ms
[0.247s][info][gc          ] GC(8) Concurrent Mark Cycle
...
[0.247s][info][gc,marking  ] GC(8) Concurrent Mark
[0.247s][info][gc,marking  ] GC(8) Concurrent Mark From Roots
[0.248s][info][gc,marking  ] GC(8) Concurrent Mark From Roots 1.336ms
...
[0.249s][info][gc          ] GC(8) Pause Remark 44M->19M(57M) 0.514ms
[0.249s][info][gc,marking  ] GC(8) Concurrent Mark 2.035ms
[0.249s][info][gc,marking  ] GC(8) Concurrent Rebuild Remembered Sets and Scrub Regions
[0.250s][info][gc,marking  ] GC(8) Concurrent Rebuild Remembered Sets and Scrub Regions 0.470ms
[0.250s][info][gc          ] GC(8) Pause Cleanup 20M->20M(57M) 0.074ms
...
[0.250s][info][gc          ] GC(8) Concurrent Mark Cycle 3.101ms
[0.253s][info][gc,heap     ] GC(9) Old regions: 16->16
...
[0.253s][info][gc          ] GC(9) Pause Young (Prepare Mixed) (G1 Evacuation Pause) 26M->15M(57M) 1.057ms
...
[0.265s][info][gc,heap     ] GC(10) Old regions: 16->13
...
[0.265s][info][gc          ] GC(10) Pause Young (Mixed) (G1 Evacuation Pause) 38M->13M(57M) 1.306ms

What this code does

  • -Xlog:gc* prints every GC-related line, with tags such as gc,marking and gc,heap. Only the lines with "Pause" stopped the program, and here each took about 0.5 ms or less; the gc,marking steps ran beside the program.
  • "Old regions: 16->13" shows the mixed collection GC(10) cleaning 3 old regions. This is a separate run of the same program, so its numbers differ a little from Example 4; lines marked ... were trimmed.

G1 then adjusts that start point at run time from what it measures. One cycle has these steps:

  1. Concurrent Start: a normal young pause that also records the starting points for marking.
  2. Concurrent Mark: marking runs beside the program, using a few GC threads.
  3. Remark: a short pause that finishes marking. Old regions found completely empty are freed here.
  4. Cleanup: a short pause that picks the old regions worth cleaning, then a Prepare Mixed young pause.
  5. Mixed collections clean those old regions a few at a time.

Order of execution

Put one G1 marking cycle in order

Tap the steps in the order they happen.

If marking cannot finish before the heap fills up, G1 falls back to "Pause Full (G1 Compaction Pause)", a stop-the-world collection of the whole heap. That is the slow path to avoid.

Garbage first: the regions with the most garbage

Garbage-First is the rule behind the name G1: in each mixed collection, clean the old regions with the most garbage first. A region with little live data is cheap to clean, because only its live objects are copied, and it frees the most memory.

Example 6 · Choosing old regions within a pause budget (a simplified model)

GarbageFirstDemo.javaJava
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
class Region {    final String name;    final int liveKb;                 // data still in use: must be copied    static final int SIZE_KB = 1024;
    Region(String name, int liveKb) {        this.name = name;        this.liveKb = liveKb;    }
    int garbageKb() {        return SIZE_KB - liveKb;    }
    double copyCostMs() {        return liveKb * 0.002;        // simplified model: 0.002 ms per KB copied    }}
public class GarbageFirstDemo {    public static void main(String[] args) {        List<Region> oldRegions = new ArrayList<>(List.of(                new Region("R1", 900), new Region("R2", 100), new Region("R3", 500),                new Region("R4", 20), new Region("R5", 700), new Region("R6", 300)));        double budgetMs = 2.0;
        oldRegions.sort(Comparator.comparingInt(Region::garbageKb).reversed());
        double usedMs = 0;        int freedKb = 0;        for (Region r : oldRegions) {            if (usedMs + r.copyCostMs() > budgetMs) {                break;                // the next region would break the pause goal            }            usedMs += r.copyCostMs();            freedKb += r.garbageKb();            System.out.printf("Collect %s: garbage %d KB, copy %d KB, %.2f ms%n",                    r.name, r.garbageKb(), r.liveKb, r.copyCostMs());        }        System.out.printf("Freed %d KB in %.2f ms of a %.1f ms budget%n", freedKb, usedMs, budgetMs);    }}
Output
Collect R4: garbage 1004 KB, copy 20 KB, 0.04 ms
Collect R2: garbage 924 KB, copy 100 KB, 0.20 ms
Collect R6: garbage 724 KB, copy 300 KB, 0.60 ms
Collect R3: garbage 524 KB, copy 500 KB, 1.00 ms
Freed 3176 KB in 1.84 ms of a 2.0 ms budget

What this code does

  • This is a teaching model, not G1's real code: each region is 1 MB, copying costs 0.002 ms per KB of live data, and the pause has 2 ms left for old regions.
  • Sorting by garbage puts R4 (only 20 KB live) first. The loop stops before R5 because its 700 KB of live data would break the budget, so the costly, mostly-live regions R5 and R1 wait.

So G1 gets the most free space for each millisecond of pause. G1 spreads the chosen regions over up to 8 mixed collections (-XX:G1MixedGCCountTarget, default 8). It stops when the garbage left in the chosen regions is at most 5% of the heap (-XX:G1HeapWastePercent, default 5), because cleaning regions that are almost all live costs much and frees little.

Next step

Check your understanding

12 quick questions