Skip to lesson

Stop-the-world pauses

While some garbage collection work runs, every application thread is stopped. For a few milliseconds your server answers nobody. Knowing why those pauses exist, how long they are and what can run beside your code is the key to fast, smooth Java services.

Why application threads must stop for some GC work

A stop-the-world pause is when the garbage collector stops all application threads for a moment to do part of its work safely.

A stop-the-world (STW) pause is a period in which the JVM stops all application threads so the garbage collector can work on the heap alone. In G1 logs every line that starts with Pause is one.

Example 1 · Measuring stalls from inside a booking loop

HiccupDemo.javaJava
import java.lang.management.GarbageCollectorMXBean;import java.lang.management.ManagementFactory;import java.util.ArrayDeque;import java.util.Deque;
public class HiccupDemo {    public static void main(String[] args) {        Deque<byte[]> recentBookings = new ArrayDeque<>();        long longestGap = 0;        int gapsOver1ms = 0;        long last = System.nanoTime();        for (int i = 0; i < 200_000; i++) {            recentBookings.addLast(new byte[2_000]);     // a 2 KB booking record            if (recentBookings.size() > 10_000) {        // keep the latest 10,000                recentBookings.removeFirst();            }            long now = System.nanoTime();            long gap = now - last;                       // time since the previous booking            longestGap = Math.max(longestGap, gap);            if (gap > 1_000_000) {                gapsOver1ms++;            }            last = now;        }        System.out.printf("Longest stall between two bookings: %.1f ms%n", longestGap / 1e6);        System.out.println("Stalls over 1 ms: " + gapsOver1ms);        for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {            System.out.println(gc.getName() + ": " + gc.getCollectionCount() + " collections, "                    + gc.getCollectionTime() + " ms");        }    }}
Sample output
Longest stall between two bookings: 19.1 ms
Stalls over 1 ms: 19
G1 Young Generation: 13 collections, 119 ms
G1 Concurrent GC: 6 collections, 1 ms
G1 Old Generation: 0 collections, 0 ms

What this code does

  • One booking normally takes far less than a microsecond, yet once the loop stalled for 19 ms. The program did nothing wrong: its thread was stopped for a GC pause. The 13 young collections took 119 ms in total.
  • Stalls can also come from the JIT or the operating system, so compare with the GC log (next examples). G1 Concurrent GC is a Java 21 name (Java 17 lists only the young and old beans); your numbers will differ.

The reason is simple: your threads keep changing references. If the collector moves an object while a thread is writing to it, or scans a thread's stack while that thread is changing it, references could end up pointing to the wrong place. Stopping everyone makes the roots and the object graph hold still. To the user a pause looks like a hang. A booking request that normally takes 2 ms takes 20 ms if an 18 ms pause starts in the middle of it.

Safepoints in simple terms

A safepoint is a place in the running code where a thread can stop safely, because the JVM knows exactly which stack slots and registers hold references there.

Example 2 · Safepoint log: the wait before the pause

Terminal
java -Xlog:gc,safepoint HiccupDemo
Sample output
[0.018s][info][gc] Using G1
[0.258s][info][gc] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 23M->20M(118M) 13.338ms
[0.258s][info][safepoint] Safepoint "G1CollectForAllocation", Time since last: 85503600 ns, Reaching safepoint: 15783200 ns, Cleanup: 48200 ns, At safepoint: 13459900 ns, Total: 29291300 ns
[0.271s][info][gc       ] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 34M->32M(118M) 7.800ms
[0.271s][info][safepoint] Safepoint "G1CollectForAllocation", Time since last: 5486500 ns, Reaching safepoint: 6000 ns, Cleanup: 5500 ns, At safepoint: 7914600 ns, Total: 7926100 ns
...
Longest stall between two bookings: 29.4 ms
...

What this code does

  • "Reaching safepoint" is the time to safepoint. At GC(0) it was 15.8 ms, longer than the 13.3 ms of GC work itself, so the threads were held for 29.3 ms in total: exactly the longest stall the program measured.
  • At GC(1) the threads reached the safepoint in 6 microseconds. A long time to safepoint is rare but real, and the GC line alone does not show it; -Xlog:safepoint does.

Threads do not stop anywhere; when the JVM asks for a pause, each thread runs on to its next safepoint poll, a quick check the JIT puts at places such as method returns and loop back-jumps (simplified). Only when all threads have reached a safepoint does the pause really start. The wait for the slowest thread is the time to safepoint, and it adds to every pause. Threads running native code or blocked count as already safe. On Java 10 and later with G1, the JIT also adds polls inside long counted loops (UseCountedLoopSafepoints is true with G1, false with Parallel on Java 21), so one big loop cannot hold up the whole JVM. Safepoints are not only for GC: thread dumps, some JIT changes and other JVM operations use them too. -Xlog:safepoint (Java 9 and later) shows each one.

Concurrent phases that run beside your code

A concurrent phase is GC work done by GC threads while your application threads keep running. In G1, marking the old generation is concurrent: the Concurrent Mark Cycle can take tens of milliseconds, but the program pauses only for the short Remark and Cleanup steps.

Example 3 · Concurrent marking beside the program

Terminal
java -Xlog:gc HiccupDemo
Sample output
...
[0.233s][info][gc] GC(4) Pause Young (Concurrent Start) (G1 Evacuation Pause) 80M->77M(354M) 11.454ms
[0.233s][info][gc] GC(5) Concurrent Mark Cycle
[0.262s][info][gc] GC(5) Pause Remark 113M->62M(87M) 0.505ms
[0.269s][info][gc] GC(5) Pause Cleanup 63M->63M(87M) 0.098ms
[0.269s][info][gc] GC(5) Concurrent Mark Cycle 35.766ms
[0.294s][info][gc] GC(6) Pause Young (Prepare Mixed) (G1 Evacuation Pause) 87M->43M(107M) 14.176ms
...

What this code does

  • The marking cycle GC(5) took 35.8 ms from start to end, but the program was stopped for only 0.5 ms (Remark) and 0.1 ms (Cleanup). The rest ran on GC threads while bookings continued.
  • Notice the young pause GC(6) right after: it took 14 ms, almost 30 times the Remark pause. In G1 the young and mixed evacuation pauses, not marking, are usually the longest ones.

Concurrent work is not free. GC threads use CPU cores your program could have used, and the JIT adds barriers to reference reads or writes so the collector can follow the changes your code makes. ZGC and Shenandoah go further and move objects concurrently too, which keeps their pauses very short, usually well under a millisecond on Java 17 and 21; the next module compares the collectors.

Latency, throughput and memory footprint: the three trade-offs

Every collector balances three goals: latency (how long one pause lasts), throughput (the share of time spent on your own work, not on GC) and footprint (how much memory the JVM needs).

Example 4 · Comparing GC profiles on the three goals (made-up numbers)

TradeOffDemo.javaJava
class GcProfile {    String name;    int pauses;            // pauses in a 60-second run    double pauseMs;        // length of each pause    double concurrentCpu;  // % of CPU used by GC threads while the program runs    int heapMb;
    GcProfile(String name, int pauses, double pauseMs, double concurrentCpu, int heapMb) {        this.name = name;        this.pauses = pauses;        this.pauseMs = pauseMs;        this.concurrentCpu = concurrentCpu;        this.heapMb = heapMb;    }
    double throughput() {        double pausedPercent = pauses * pauseMs / 60_000 * 100;        return 100 - pausedPercent - concurrentCpu;    }}
public class TradeOffDemo {    public static void main(String[] args) {        GcProfile[] profiles = {            new GcProfile("Few long pauses", 6, 300, 0, 2048),            new GcProfile("Balanced", 40, 25, 2, 2048),            new GcProfile("Short pauses", 200, 0.5, 6, 3072),            new GcProfile("Small heap", 120, 25, 2, 512)        };        System.out.println("Profile          Throughput  Longest pause  Heap");        for (GcProfile p : profiles) {            System.out.println(String.format("%-16s %9.1f%% %11.1f ms %5d MB",                    p.name, p.throughput(), p.pauseMs, p.heapMb));        }    }}
Output
Profile          Throughput  Longest pause  Heap
Few long pauses       97.0%       300.0 ms  2048 MB
Balanced              96.3%        25.0 ms  2048 MB
Short pauses          93.8%         0.5 ms  3072 MB
Small heap            93.0%        25.0 ms   512 MB

What this code does

  • The numbers are invented to show the shape of the trade-off over a 60-second run. Throughput here is 100% minus the paused share minus the CPU share of concurrent GC threads.
  • "Few long pauses" wins on throughput but a 300 ms freeze would hurt a payment API. "Short pauses" gives tiny pauses but costs CPU and memory. "Small heap" saves memory but collects so often that it loses throughput.
  • Latency: how long a single pause is. It matters for user-facing services such as a booking site or a payment API.
  • Throughput: the share of time and CPU spent on your own work, not on GC. It matters for batch jobs such as a nightly marks report.
  • Footprint: how much memory the JVM needs.

You can usually improve two of them by giving up some of the third. A bigger heap means fewer collections (better throughput) but a larger footprint. Shorter pauses need more concurrent work (lower throughput). On HotSpot, Parallel aims at throughput, G1 balances the three with a pause-time goal (MaxGCPauseMillis, 200 ms by default), and ZGC aims at the shortest pauses.

Pick the goal first, then the collector and heap size. "Make GC faster" is not a goal; "keep 99% of booking requests under 50 ms" is.

Next step

Check your understanding

12 quick questions