Skip to lesson

Watch the heap with jstat

A heap summary is one photo; a memory problem is a story that unfolds over minutes. jstat prints a new line of heap and GC numbers every second or every few seconds, so you can watch the story happen in your terminal.

jstat -gc: live heap numbers

jstat is the JDK tool that prints garbage collection and memory counters of a running JVM, one line per interval, so you can watch the heap change over time.

jstat (JVM Statistics Monitoring Tool) prints garbage collection counters of a running JVM, one line per interval. jstat -gc <pid> 1000 prints a line every 1000 milliseconds until you press Ctrl+C; jstat -gc <pid> 1000 5 stops after 5 lines.

Example 1 · Live numbers every second with jstat -gc

Terminal
jstat -gc <pid> 1000 3
Sample output
    S0C         S1C         S0U         S1U          EC           EU           OC           OU          MC         MU       CCSC      CCSU     YGC     YGCT     FGC    FGCT     CGC    CGCT       GCT
        0.0      3072.0         0.0      3009.4      35840.0       7168.0      81920.0          0.0      512.0      332.2     128.0      21.3      1     0.003     0     0.000     0     0.000     0.003
        0.0      3072.0         0.0      3009.4      35840.0      17408.0      81920.0          0.0      512.0      332.2     128.0      21.3      1     0.003     0     0.000     0     0.000     0.003
        0.0      3072.0         0.0      3009.4      35840.0      26624.0      81920.0          0.0      512.0      332.2     128.0      21.3      1     0.003     0     0.000     0     0.000     0.003

What this code does

  • This is ResultsServer from the jps and jcmd lesson, 2 seconds after start, on JDK 21 with G1. Eden used (EU) grows from 7168 KB to 26624 KB in two seconds: new objects are being created all the time.
  • Eden capacity (EC) is 35840 KB, about 35 MB. When EU reaches it, a young GC runs, YGC goes up by one and EU drops back near zero. The old generation (OU) is still empty.

You can also write the interval as 1s.

With -gc, every size is in KB. Names ending in C are capacities (space reserved now), names ending in U are used space:

  • S0C/S1C, S0U/S1U: the two survivor spaces.
  • EC/EU: eden, where new objects are created.
  • OC/OU: the old generation, where long-lived objects end up.
  • MC/MU and CCSC/CCSU: metaspace and compressed class space, for class metadata.
jstat reads counters the JVM already keeps, so it is very cheap. It is safe to leave it running on a busy server for an hour.

jstat -gcutil: percentages at a glance

jstat -gcutil prints the same areas as percentages of their current capacity: S0, S1, E (eden), O (old), M (metaspace) and CCS. It fits on one screen line and is the quickest way to see "how full is each area right now".

Example 2 · Percentages every 10 seconds with jstat -gcutil

Terminal
java -Xms256m -Xmx256m HealthyServerjstat -gcutil <pid> 10s 9
Sample output
  S0     S1     E      O      M     CCS    YGC     YGCT     FGC    FGCT     CGC    CGCT       GCT
     -  96.52  74.29   0.00  65.35  16.67      1     0.002     0     0.000     0     0.000     0.002
     -  88.36  61.54   1.09  65.98  16.67      2     0.005     0     0.000     0     0.000     0.005
     -  97.91  26.11   1.26  66.21  16.67      3     0.009     0     0.000     0     0.000     0.009
     -  97.91  86.62   1.26  66.21  16.67      3     0.009     0     0.000     0     0.000     0.009
     -  99.82  45.86   1.26  66.21  16.67      4     0.013     0     0.000     0     0.000     0.013
     -  97.51  11.46   1.26  66.21  16.67      5     0.019     0     0.000     0     0.000     0.019
     -  97.51  71.97   1.26  66.21  16.67      5     0.019     0     0.000     0     0.000     0.019
     -  97.10  31.21   1.26  66.21  16.67      6     0.025     0     0.000     0     0.000     0.025
     -  97.10  91.08   1.26  66.21  16.67      6     0.025     0     0.000     0     0.000     0.025

What this code does

  • HealthyServer is the same results server with the bug fixed: it keeps only the last 200 sessions (if (SESSIONS.size() > 200) SESSIONS.remove(0);). It was started with a fixed 256 MB heap so the percentages are easy to compare.
  • Eden (E) swings between 11% and 91% as young GCs empty it. The old generation (O) settles at 1.26% and stays there for 80 seconds: whatever reaches the old generation is later freed. S0 shows - because G1 had no regions in that survivor space.

A - means the area has zero capacity at that moment. With G1 (the default collector on most machines since Java 9) you often see one survivor column as -, because G1 sizes the young areas region by region. Percentages are of the current capacity, and the JVM can grow or shrink an area between lines. To compare memory over a long time, use the KB numbers from -gc, especially OU.

YGC, FGC and GC time columns

The last columns count collections since the JVM started. YGC is the number of young collections and YGCT their total time in seconds. FGC and FGCT are the same for full collections. With G1, CGC and CGCT count the short pauses of its concurrent cycles.

Example 3 · The same counters from inside Java

GcCountersDemo.javaJava
import java.lang.management.GarbageCollectorMXBean;import java.lang.management.ManagementFactory;import java.lang.management.MemoryUsage;import java.util.ArrayList;import java.util.List;
public class GcCountersDemo {    public static void main(String[] args) {        List<String> receipts = new ArrayList<>();        for (int i = 0; i < 3_000_000; i++) {            String receipt = "UPI-" + i + "-Rs-" + (i % 500);     // short-lived garbage            if (i % 1000 == 0) {                receipts.add(receipt);                            // a few are kept            }        }        System.out.println("Receipts kept: " + receipts.size());
        for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {            System.out.println(gc.getName() + ": " + gc.getCollectionCount()                    + " collections, " + gc.getCollectionTime() + " ms");        }        MemoryUsage heap = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();        System.out.println("Heap used: " + heap.getUsed() / (1024 * 1024) + " MB of "                + heap.getCommitted() / (1024 * 1024) + " MB committed");    }}
Sample output
Receipts kept: 3000
G1 Young Generation: 3 collections, 6 ms
G1 Concurrent GC: 0 collections, 0 ms
G1 Old Generation: 0 collections, 0 ms
Heap used: 55 MB of 118 MB committed

What this code does

  • Each GarbageCollectorMXBean is one collector with a count and a total time in milliseconds, the same numbers jstat shows as YGC/YGCT and so on. The counts and times change on every run and every machine.
  • The bean names depend on the collector and the version: this run is G1 on JDK 21. Java 19 printed only "G1 Young Generation" and "G1 Old Generation"; "G1 Concurrent GC" was added in a later version.

Example 4 · Turn two jstat lines into GC frequency and GC share

GcShareDemo.javaJava
public class GcShareDemo {    // Two real jstat -gcutil lines from the results server, taken 70 seconds apart    static final String FIRST = "     -  87.41  94.37   2.54  65.34  16.67      2     0.020     0     0.000     0     0.000     0.020";    static final String LAST  = "     -  94.35  53.42  65.81  65.53  16.67      7     0.109     0     0.000     0     0.000     0.109";
    public static void main(String[] args) {        String[] a = FIRST.trim().split("\\s+");        String[] b = LAST.trim().split("\\s+");        // columns: S0 S1 E O M CCS YGC YGCT FGC FGCT CGC CGCT GCT        int youngGcs = Integer.parseInt(b[6]) - Integer.parseInt(a[6]);        int fullGcs = Integer.parseInt(b[8]) - Integer.parseInt(a[8]);        double gcSeconds = Double.parseDouble(b[12]) - Double.parseDouble(a[12]);        int wallSeconds = 70;
        System.out.println("Young GCs in 70 s: " + youngGcs);        System.out.println("Full GCs in 70 s: " + fullGcs);        System.out.printf("Time spent in GC: %.0f ms%n", gcSeconds * 1000);        System.out.printf("Share of time in GC: %.2f%%%n", 100 * gcSeconds / wallSeconds);        System.out.println("Old generation: " + a[3] + "% -> " + b[3] + "%");    }}
Output
Young GCs in 70 s: 5
Full GCs in 70 s: 0
Time spent in GC: 89 ms
Share of time in GC: 0.13%
Old generation: 2.54% -> 65.81%

What this code does

  • The two lines are real jstat -gcutil output from the leaking ResultsServer, 70 seconds apart. Subtracting YGC gives 5 young GCs; subtracting GCT gives 0.089 seconds of GC, only 0.13% of the time.
  • So GC is cheap here, yet the old generation went from 2.54% to 65.81%. A leak does not slow GC down at first; it quietly fills the heap. That is why you look at O and OU, not only at GC time.

GCT is the total of all GC time. The counters only grow, so one line alone says little. Subtract two lines: the difference in YGC over 60 seconds is how often young GCs run, and the difference in GCT divided by 60 is the share of time spent in GC. A healthy service usually spends well under a few percent of its time in GC. The same counters are available inside Java through GarbageCollectorMXBean, which is how monitoring dashboards read them.

Predict the output

Read the jstat lines

Each round shows jstat -gcutil lines. Pick what they tell you.

Round 1 of 3

Two lines taken five minutes apart (sample values).

S0 S1 E O M CCS YGC YGCT FGC FGCT GCT
- 97.10 31.21 1.26 66.21 16.67 6 0.025 0 0.000 0.025
- 96.80 18.40 1.26 66.21 16.67 12 0.051 0 0.000 0.051

Spotting an old generation that never shrinks

Young collections empty eden all the time, so eden going up and down tells you nothing about a leak. Watch OU, the old generation used, right after each GC (each time YGC or FGC goes up).

Two charts of heap used. Healthy: a saw shape whose low points after each GC stay level, so OU is flat. Leak: every low point is higher than the last until the limit is reached, FGC rises and an OutOfMemoryError follows.

Example 5 · A leak in jstat: old generation after every GC

Terminal
java -Xms256m -Xmx256m -Xlog:gc:file=gc-leak.log ResultsServerjstat -gc <pid> 10s 8
Sample output
    S0C         S1C         S0U         S1U          EC           EU           OC           OU          MC         MU       CCSC      CCSU     YGC     YGCT     FGC    FGCT     CGC    CGCT       GCT
        0.0      4096.0         0.0      3580.2     145408.0     137216.0     112640.0       2861.1      512.0      334.6     128.0      21.3      2     0.020     0     0.000     0     0.000     0.020
        0.0     18432.0         0.0     18229.0     146432.0      80896.0      97280.0       2861.1      512.0      335.5     128.0      21.3      3     0.030     0     0.000     0     0.000     0.030
        0.0     14336.0         0.0     14211.2     150528.0      39936.0      97280.0      21030.9      512.0      335.5     128.0      21.3      4     0.048     0     0.000     0     0.000     0.048
        0.0     14336.0         0.0     14211.2     150528.0     136192.0      97280.0      21030.9      512.0      335.5     128.0      21.3      4     0.048     0     0.000     0     0.000     0.048
        0.0     15360.0         0.0     14570.6     149504.0      80896.0      97280.0      35130.8      512.0      335.5     128.0      21.3      5     0.066     0     0.000     0     0.000     0.066
        0.0     15360.0         0.0     14375.1     149504.0      37888.0      97280.0      49623.1      512.0      335.5     128.0      21.3      6     0.089     0     0.000     0     0.000     0.089
        0.0     15360.0         0.0     14375.1     149504.0     134144.0      97280.0      49623.1      512.0      335.5     128.0      21.3      6     0.089     0     0.000     0     0.000     0.089
        0.0     15360.0         0.0     14492.4     149504.0      79872.0      97280.0      64019.8      512.0      335.5     128.0      21.3      7     0.109     0     0.000     0     0.000     0.109

What this code does

  • This is the leaking ResultsServer with the same fixed 256 MB heap. Every time YGC goes up, OU steps up and never comes back: 2861 KB, 21030 KB, 35130 KB, 49623 KB, 64019 KB. In 70 seconds about 60 MB of sessions moved to the old generation and stayed.
  • Compare HealthyServer with the same heap: its old generation stayed at 1102.2 KB after every one of its GCs. The -Xlog:gc option also wrote a GC log, which tells the same story: "heap after GC" went 2M, 6M, 20M, 34M, 48M, 62M, 76M.
  • At this rate the 256 MB heap fills in a few minutes. Then FGC starts climbing and the program ends with OutOfMemoryError: Java heap space.

Example 6 · Judge the trend of OU after each GC

OldGenTrendDemo.javaJava
import java.util.List;
public class OldGenTrendDemo {    // Old generation used (OU, in KB) after each young GC, from two real jstat -gc runs    static String verdict(List<Double> oldUsedKb) {        int rises = 0;        for (int i = 1; i < oldUsedKb.size(); i++) {            if (oldUsedKb.get(i) > oldUsedKb.get(i - 1) * 1.05) {   // grew by more than 5%                rises++;            }        }        double growthMb = (oldUsedKb.get(oldUsedKb.size() - 1) - oldUsedKb.get(0)) / 1024;        String trend = rises == oldUsedKb.size() - 1 ? "grows after every GC: suspect a leak"                : rises == 0 ? "stays flat: looks healthy"                : "goes up and down: watch longer";        return String.format("%d rises, %+.1f MB, %s", rises, growthMb, trend);    }
    public static void main(String[] args) {        List<Double> resultsServer = List.of(2861.1, 21030.9, 35130.8, 49623.1, 64019.8);        List<Double> healthyServer = List.of(1102.2, 1102.2, 1102.2, 1102.2, 1102.2);
        System.out.println("Results server: " + verdict(resultsServer));        System.out.println("Healthy server: " + verdict(healthyServer));    }}
Output
Results server: 4 rises, +59.7 MB, grows after every GC: suspect a leak
Healthy server: 0 rises, +0.0 MB, stays flat: looks healthy

What this code does

  • The lists hold OU right after each young GC, taken from the two real jstat -gc runs above. The method counts how often it grew by more than 5% and how many MB it gained in total.
  • "Grows after every GC" means suspect, not proven. The next step is to confirm with a longer watch and a heap dump that shows which objects are kept.

In a healthy program it settles at a steady level. In a leaking program it climbs after every collection, because the objects that reach the old generation are still referenced and cannot be freed. The end of that story is full GCs. When the old generation is nearly full, FGC starts rising every few seconds, FGCT grows almost as fast as the clock, and the program stops doing useful work long before the OutOfMemoryError finally arrives. A rising OU is a reason to look closer, not proof. Caches filling up and the first minutes after start-up also raise it. Watch over a longer time, then take a heap dump (next lesson) to see what is actually being kept.

Next step

Check your understanding

11 quick questions