Sub topic 5
Reading garbage collection logs
This chapter assumes you can start a Java program from the command line, know what the heap is, and can read a stack trace. It covers how to turn on garbage collection (GC) logging, how to read a log line, and which patterns point to a problem.
Why read GC logs
A garbage collector reclaims memory from objects the program no longer uses. While it works, it can pause your application threads. These pauses are called stop-the-world (STW) pauses. A GC log records each collection with its timing and heap sizes. It costs very little to produce, so you can leave it on in production.
A GC log answers questions that a CPU profile cannot:
- How often does the collector run?
- How long does each pause last?
- Does memory come back after a collection, or does the heap keep growing?
Turning on unified logging
Since JDK 9, all JVM logging goes through one system called unified logging, controlled by the -Xlog option. The option has the form -Xlog:what:where:decorators.
java -Xlog:gc*:file=gc.log:time,uptime,level,tags -jar app.jarThe parts of this command are:
gc*selects thegctag and every tag that combines with it, such asgc,heapandgc,phases. Plaingcgives one summary line per collection.file=gc.logwrites to a file instead of standard output.time,uptime,level,tagsare decorators. They prefix each line with the wall-clock time, the seconds since JVM start, the log level and the tags.
To keep the file from growing without limit, add rotation: file=gc.log:time,uptime:filecount=5,filesize=20m.
On JDK 8, unified logging does not exist. Use -XX:+PrintGCDetails -XX:+PrintGCDateStamps -Xloggc:gc.log instead. The line format differs from what is shown below.
Anatomy of a log line
With only -Xlog:gc, a young collection under G1 (the default collector since JDK 9) looks like this:
[2.345s][info][gc] GC(12) Pause Young (Normal) (G1 Evacuation Pause) 512M->96M(1024M) 8.213ms| Part | Meaning |
|---|---|
| `[2.345s]` | Uptime when the line was written |
| `GC(12)` | The twelfth collection since JVM start |
| `Pause Young (Normal)` | A young-generation pause. "Normal" means it was triggered by the young region filling up |
| `G1 Evacuation Pause` | The cause: G1 copied live objects out of regions |
| `512M->96M(1024M)` | Heap used before, heap used after, and total committed heap |
| `8.213ms` | How long application threads were stopped |
The most useful number is the "after" value. It tells you how much memory is live data. If it is 96M after a collection, the program holds about 96 MB of reachable objects at that moment.
Common collection types
Different pause names mean different things.
| Log text | What it means | Concern level |
|---|---|---|
| `Pause Young (Normal)` | Routine young collection | Normal, watch frequency |
| `Pause Young (Concurrent Start)` | A young pause that also starts a concurrent marking cycle | Normal |
| `Pause Remark`, `Pause Cleanup` | Short STW phases of concurrent marking | Normal if short |
| `Pause Young (Mixed)` | Collects young regions plus some old regions | Normal |
| `Pause Full` | A full, single-threaded-style compaction of the whole heap | Investigate |
| `To-space exhausted` | G1 ran out of space to copy survivors into | Investigate |
A Full GC under G1 is a failure mode. G1 normally avoids it by collecting old regions concurrently. If you see Pause Full (Allocation Failure), the collector could not keep up with the allocation rate or the heap is too small for the live data.
Reading the pattern, not one line
One line tells you little. The shape of many lines tells you a lot. Look for three things.
- The floor of the "after" values. Take the heap used after each collection. If that floor rises steadily over minutes or hours and never drops back, objects are being retained. This suggests a memory leak. The heap dump chapter covers how to find the cause.
- Collection frequency. If young collections run every 50 ms, the program allocates quickly. High allocation rate means high GC pressure, even if each pause is short.
- Pause duration against your goal. If your latency goal is a 99th percentile of 200 ms and you see 400 ms pauses, GC is a likely cause.
Measuring with a live process
You do not always have a log file. jstat samples a running JVM without a restart.
jstat -gcutil <pid> 1000This prints one row per second. The columns include S0 and S1 (survivor spaces), E (eden), O (old generation), M (metaspace), YGC and FGC (young and full collection counts), and GCT (total GC time in seconds). The values for E, O and similar columns are percentages of the space's capacity. Watch O and FGC. If O climbs and FGC increases, the old generation is filling up.
A useful quick check is the share of time spent in GC. Divide the change in GCT by the elapsed time. If the JVM spends more than about 5 to 10 percent of wall time in GC, collection is costing real throughput.
A worked example
The Slow program from the tutorial concatenates strings in a loop. Each s += i creates a new String, copying all earlier characters. That produces a lot of short-lived garbage.
public class Slow {
public static void main(String[] args) {
long start = System.nanoTime();
for (int round = 0; round < 200; round++) {
String s = "";
for (int i = 0; i < 5_000; i++) {
s += i;
}
if (s.length() == 0) {
System.out.println("unreachable");
}
}
System.out.println((System.nanoTime() - start) / 1_000_000 + " ms");
}
}Run it with a small heap and GC logging:
javac Slow.java
java -Xmx64m -Xlog:gc:file=gc.log:uptime SlowYou should see many Pause Young lines in gc.log, each with a small "after" value such as 3M or 4M. That is the signature of high allocation with almost no retention. The "after" floor stays flat, so this is not a leak. The collections are frequent because the program creates garbage quickly.
You can count the collections with a shell command:
grep -c "Pause Young" gc.logA count in the hundreds or thousands for a program this short confirms heavy allocation. Fixing the code to use a StringBuilder should drop the count sharply. You would then measure again, which the optimize-and-verify chapter covers.
Edge cases and pitfalls
- Concurrent phases are not pauses. Lines such as
Concurrent Mark Cyclerun alongside application threads. Their duration does not stop your code. Only lines starting withPausecount as STW time. - Pause time is not the whole cost. A concurrent collector uses CPU on other threads. A log with short pauses can still hide a program that burns a large share of its CPU on GC.
- Heap sizing hides problems. A larger heap makes collections rarer but not free. A leak in a large heap just takes longer to show up.
- Containers change the defaults. In a container, the JVM sizes the heap from the container memory limit. Log the heap settings at startup.
-Xlog:gc+initprints the chosen collector, heap region size and maximum heap. - Different collectors, different lines. Parallel GC, ZGC and Shenandoah use different pause names and formats. The ideas are the same: find pauses, read the after-GC heap, and watch frequency.
- Do not trust one run. GC behavior depends on timing and heap state. Compare logs from comparable runs.
Quick checklist
- Enable
-Xlog:gc*with file output and rotation. - Find the heap-after-GC values and check whether the floor is flat.
- Count and time the
Pauselines against your latency goal. - Look for
Pause FullandTo-space exhausted. - Decide the next tool: a heap dump for a leak, an allocation profile for pressure, or a collector or heap change for long pauses.
Exercise
A G1 log shows these heap-after-GC values for successive Pause Young lines over ten minutes: 80M, 95M, 112M, 130M, 149M, 170M. Pauses are all under 10 ms. Is GC healthy, and what do you do next?
Show answer
The pauses are short, but the heap-after-GC floor rises steadily, which means live data is growing. This points to a memory leak or unbounded cache, and it will eventually cause Full GCs or an OutOfMemoryError. Take a heap dump with jcmd <pid> GC.heap_dump and look for the object types that dominate retained memory.
Exercise
A log has 800 Pause Young lines in 60 seconds. Each is 2 ms, and the after-GC heap stays near 20M. What is the likely problem, and which tool do you use next?
Show answer
The program has a high allocation rate with little retention, so there is GC pressure but no leak. Total pause time is about 1.6 seconds out of 60, and the collector also uses CPU. Use an allocation profile in Java Flight Recorder to find which code creates the most objects.