Skip to lesson

Garbage collectors and options practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Choosing a collector and JVM options is an experiment: run the same program with different settings, read the GC logs, and keep what the numbers support. A small set of good defaults covers most small applications.

Comparing collectors on one program

A fair comparison runs the same program, with the same heap size and the same input, and changes only the collector flag. Then the GC logs differ only because of the collector.

Example 1 · A small tool: pause statistics from a GC log file

PauseStats.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;
public class PauseStats {    public static void main(String[] args) throws IOException {        if (args.length == 0) {            System.out.println("Usage: java PauseStats <gc log file>");            return;        }        Path log = Path.of(args[0]);        int pauses = 0;        double totalMs = 0;        double longestMs = 0;        for (String line : Files.readAllLines(log)) {            if (line.contains("Pause") && line.endsWith("ms")) {     // one finished pause                String last = line.substring(line.lastIndexOf(' ') + 1);                double ms = Double.parseDouble(last.substring(0, last.length() - 2));                pauses++;                totalMs += ms;                longestMs = Math.max(longestMs, ms);            }        }        System.out.printf("%s: %d pauses, total %.3f ms, longest %.3f ms%n",                log.getFileName(), pauses, totalMs, longestMs);    }}
Output
Usage: java PauseStats <gc log file>

What this code does

  • Given a log file name, it counts the lines that describe a finished pause (they contain "Pause" and end in "ms"), adds up their times and keeps the longest. With no file name it prints how to use it, as here.
  • The same rule works for Serial, Parallel and G1 summary lines and for ZGC's Pause ... phase lines, so one tool can compare all four collectors.

Example 2 · One program, four collectors

Terminal
java -XX:+UseSerialGC -Xmx256m "-Xlog:gc,gc+phases:file=Serial.log" FestTicketsDemojava -XX:+UseParallelGC -Xmx256m "-Xlog:gc,gc+phases:file=Parallel.log" FestTicketsDemojava -XX:+UseG1GC -Xmx256m "-Xlog:gc,gc+phases:file=G1.log" FestTicketsDemojava -XX:+UseZGC -Xmx256m "-Xlog:gc,gc+phases:file=Z.log" FestTicketsDemojava PauseStats Serial.logjava PauseStats Parallel.logjava PauseStats G1.logjava PauseStats Z.log
Sample output
...
Serial.log: 7 pauses, total 10.945 ms, longest 2.180 ms
Parallel.log: 5 pauses, total 7.903 ms, longest 2.271 ms
G1.log: 4 pauses, total 9.586 ms, longest 3.299 ms
Z.log: 7 pauses, total 0.095 ms, longest 0.024 ms

What this code does

  • Same program, same 256 MB heap: Serial needed 7 pauses, Parallel 5 and G1 4, each a few milliseconds; ZGC's 7 tiny pauses added up to less than 0.1 ms. The ... stands for the program's own output from the four runs.
  • This was one of four repeats. In earlier repeats on the same busy machine, Parallel's longest pause reached 271 ms once and G1's 46 ms once: one run is not enough to judge a collector.

Short runs on a laptop are noisy: other programs, power saving and JVM warm-up all move the numbers. Run each setting several times and look at the typical (median) value, not the single best or worst run. Compare what matters for the application: the longest pause for a booking API, the total GC time for a batch job.

When a log file already exists, the JVM renames it at start-up (G1.log becomes G1.log.0, and so on) before writing a new one, so earlier runs are kept.

Heap limits and how often GC runs

The heap size decides how often collections happen. With a small heap, eden fills quickly and the collector runs again and again; with a larger heap, the same garbage is cleaned in fewer, bigger collections.

Example 3 · The same job with four heap settings

Terminal
java -Xmx16m -Xlog:gc MarksheetBatchDemo | grep -c Pausejava -Xmx32m -Xlog:gc MarksheetBatchDemo | grep -c Pausejava -Xmx128m -Xlog:gc MarksheetBatchDemo | grep -c Pausejava -Xms512m -Xmx512m -Xlog:gc MarksheetBatchDemo | grep -c Pause
Sample output
30
13
5
2

What this code does

  • grep -c Pause counts the pause lines. MarksheetBatchDemo needed 30 pauses with a 16 MB heap, 13 with 32 MB, 5 with 128 MB, and only 2 with a fixed 512 MB heap.
  • Each pause was still short, because almost every object was already garbage. A bigger heap here saves pauses, not memory leaks.

For short-lived garbage the total GC work hardly changes, because a young collection copies only the few objects that are still live. What changes is the number of pauses and, with a fixed -Xms = -Xmx, whether the JVM spends time growing the heap.

Naming the problem in a GC log

Naming the problem means matching a pattern in the log to its usual cause, so you know where to look next. Four patterns cover most cases in a first job.

Example 4 · Naming the problem from a few log lines

NameTheProblem.javaJava
public class NameTheProblem {    static String name(String[] log) {        int full = 0;        int explicitGc = 0;        int humongous = 0;        int firstAfter = -1;        int lastAfter = 0;        for (String line : log) {            if (line.contains("Pause Full")) {                full++;            }            if (line.contains("(System.gc())")) {                explicitGc++;            }            if (line.contains("G1 Humongous Allocation")) {                humongous++;            }            int arrow = line.indexOf("->");            if (arrow > 0) {                int after = Integer.parseInt(line.substring(arrow + 2, line.indexOf('M', arrow)));                if (firstAfter < 0) {                    firstAfter = after;                }                lastAfter = after;            }        }        if (explicitGc > 0) {            return "System.gc() in the code: remove the call";        }        if (full > 0 && lastAfter > firstAfter) {            return "heap after GC rising and Full GCs: memory leak";        }        if (humongous * 2 >= log.length) {            return "many large arrays: humongous allocations";        }        return "healthy";    }
    public static void main(String[] args) {        String[][] logs = {   // real -Xlog:gc lines from this module's runs, trimmed            {"GC(0) Pause Young (Normal) (G1 Evacuation Pause) 23M->0M(48M) 2.954ms",             "GC(13) Pause Young (Normal) (G1 Evacuation Pause) 27M->0M(48M) 1.524ms"},            {"GC(0) Pause Young (Normal) (G1 Evacuation Pause) 23M->2M(48M) 30.654ms",             "GC(20) Pause Young (Normal) (G1 Evacuation Pause) 42M->35M(48M) 1.519ms",             "GC(85) Pause Full (G1 Compaction Pause) 46M->45M(48M) 2.727ms"},            {"GC(0) Pause Young (Concurrent Start) (G1 Humongous Allocation) 56M->54M(118M) 2.595ms",             "GC(2) Pause Full (System.gc()) 61M->0M(8M) 3.922ms"},            {"GC(0) Pause Young (Concurrent Start) (G1 Humongous Allocation) 30M->0M(64M) 4.084ms",             "GC(2) Pause Young (Concurrent Start) (G1 Humongous Allocation) 28M->0M(64M) 1.468ms",             "GC(4) Pause Young (Concurrent Start) (G1 Humongous Allocation) 28M->0M(64M) 1.492ms"}        };        String[] apps = {"Fixed sessions", "Leaky sessions", "Report export", "PDF generator"};        for (int i = 0; i < logs.length; i++) {            System.out.println(apps[i] + ": " + name(logs[i]));        }    }}
Output
Fixed sessions: healthy
Leaky sessions: heap after GC rising and Full GCs: memory leak
Report export: System.gc() in the code: remove the call
PDF generator: many large arrays: humongous allocations

What this code does

  • Each array holds real lines from runs in this module. The checks look for System.gc(), then a rising heap after GC with Full pauses, then mostly humongous pauses.
  • The order matters: the report-export log also has a humongous pause, but the System.gc() call is the first thing to fix.
  • Flat heap after GC, regular young pauses: healthy.
  • Heap after GC rising, then Full pauses: a leak; find what keeps objects reachable.
  • Pause Full (System.gc()): code or a library calls System.gc(); remove the call.
  • Many G1 Humongous Allocation pauses: lots of large arrays; make them smaller or reuse them.

Choosing options for a small application

A sensible option set for a small service keeps the defaults that already work well and adds only what helps you size the heap and understand problems later: a heap size on purpose, a heap dump on OutOfMemoryError, and a rotating GC log.

Example 5 · Checking a small service option set

Terminal
java -XX:MaxRAM=1g -XX:MaxRAMPercentage=75 \     -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=dumps \     "-Xlog:gc*:file=gc-%p.log:time,uptime,level,tags:filecount=5,filesize=20m" \     -XX:+PrintFlagsFinal -version | grep -E " (MaxHeapSize|UseG1GC|HeapDumpOnOutOfMemoryError|HeapDumpPath|MaxRAMPercentage) "
Sample output
openjdk version "21.0.7" 2025-04-15
...
     bool HeapDumpOnOutOfMemoryError               = true                                   {manageable} {command line}
    ccstr HeapDumpPath                             = dumps                                  {manageable} {command line}
   size_t MaxHeapSize                              = 805306368                                 {product} {ergonomic}
   double MaxRAMPercentage                         = 75.000000                                 {product} {command line}
     bool UseG1GC                                  = true                                      {product} {ergonomic}

What this code does

  • -XX:MaxRAM=1g pretends the machine has 1 GB, like a 1 GB container; 75% of it gives a 768 MB heap (805306368 bytes). G1 is still chosen automatically.
  • {command line} confirms the heap dump options and the percentage were read correctly. -version only prints the version, so nothing else runs.

Keep G1 and its 200 ms pause goal unless measurements show a need to change them. Check the result once with -XX:+PrintFlagsFinal (or jcmd <pid> VM.flags on the running service), because a typing mistake in a flag name can be silently ignored by some JDK builds.

Finish up

Mark complete & continue

Next: What a memory leak means in Java