Full GC Every 10 Minutes: A JDK 21 Diagnostic Walkthrough from jstat to JFR to a Code Fix
At 2 a.m., the monitoring group suddenly blew up: the report service's P99 latency jumped from 80ms to 8 seconds, CPU didn't rise, but the GC curve pulsed like a heartbeat. Pulling up the GC log, a Full GC every 10 minutes, each pause over 3 seconds. This isn't an isolated case — as long as a service has an 'only-in, never-out' cache, large arrays, or batch loading, G1's old generation will eventually fill up, and Full GC comes knocking. This article uses a real Spring Boot 4.1.0 application to demonstrate the complete process from discovering anomalies with jstat, locating root cause with JFR, to code fixes and JVM parameter tuning, all based on JDK 21.
Abstract: Frequent Full GC and interface stalls are the most common performance accidents in Java production environments. This article starts with the JVM heap memory model and G1 garbage collector principles, reproduces the Full GC problem caused by 'unbounded static cache growth' in a Spring Boot 4.1.0 application, and walks through the complete diagnostic process using JDK built-in tools like jstat, jcmd, JFR, and jmap. It ends with code fixes, G1 parameter tuning, and ZGC selection advice. The entire article is based on JDK 21 measurements, including fully runnable code.
1. What exactly is this problem
Frequent Full GC means the JVM heap reclaim is no longer keeping up with object creation speed, and every Full GC pauses all business threads (STW). Interface stalls are just the most visible symptom. This is not a bug in any specific framework, but a pitfall any Java service hits when memory management is unbalanced. Spring Boot applications are no exception.
First, clarify what Full GC is. JVM garbage collection falls into two categories: Minor/Young GC (only reclaims the young generation, fast, pauses under tens of milliseconds) and Full GC (reclaims the entire heap, including the old generation, slow, pauses can be seconds). In the default G1 collector in JDK 21, Full GC is single-threaded and serial. The larger the heap, the longer the pause — a Full GC on an 8GB heap pausing 3-5 seconds is common. During the pause, all request threads freeze, manifesting as: interface timeouts, connection pool exhaustion, and the GC time curve on the monitoring dashboard becoming a pulse.
Typical Full GC symptom combination:
| Symptom | Description |
|---|---|
| Interface P99 spikes | All requests queue during STW, then flood in after recovery |
| CPU low but response slow | Full GC is a memory operation, doesn't consume CPU, easily misdiagnosed as a network issue |
| Regular pauses in GC log | Full GC trigger interval is stable, indicating objects are accumulating at a fixed rate |
| Old generation usage keeps climbing | Reclamation < growth, old generation water level only rises |
What kind of code triggers Full GC? The three most common categories: First, static/singleton container cache growing without bound — static Map, static List only put and never clean, each business request keeps pushing objects into the old generation; Second, large objects entering old generation directly — in G1, objects larger than half a Region (Humongous objects) skip the young generation and go straight to old, like loading 20MB of report data at once; Third, batch loading into memory — querying hundreds of thousands of records and assembling them into a list of objects, memory bottoms out instantly.
This article solves: when Full GC is already frequent, how to use JDK built-in tools step by step to locate the root cause, how to fix the code, and how to tune JVM parameters.
2. What's the underlying principle
The root cause of Full GC is 'runaway object survival rate': objects that enter the old generation can't be reclaimed for a long time, G1's Mixed GC can't digest them, and eventually the serial Full GC is triggered as a safety net. To understand this, you need to look at the memory layout and working of G1, the default collector in JDK 21.
G1 divides the heap into Regions
G1 (Garbage First) divides the entire heap into equal-sized Regions, default between 1MB and 32MB (typically 1MB when heap < 4GB, larger Region for larger heaps). Regions are dynamically assigned roles: some are Eden (young object allocation), some Survivor (survivor objects transit), the rest Old (old generation). The young and old generations are no longer physically contiguous blocks, but rather 'logically grouped, physically scattered' sets of Regions — this is the basis for G1's predictable pauses; it only reclaims the Regions with the most garbage (hence the name Garbage First).
Object lifecycle and promotion
New objects allocate in Eden Regions. When Eden fills, Young GC triggers; survivors are copied to Survivor, aging +1 each GC, and upon reaching the threshold (default 15) they promote to Old. Two paths allow objects to enter old generation early:
- Humongous objects: an object exceeding half the Region size (e.g., Region 1MB, object 600KB), G1 places it directly in a contiguous 'humongous area', skipping the young generation. A 20MB
byte[]under this mechanism is equivalent to living in old generation immediately. - Promotion failure: when Survivor can't hold survivors during Young GC, the excess is 'prematurely promoted'.
Full GC trigger conditions
G1 normally uses two types of reclamation: Young GC (only young generation, short pause) and Mixed GC (young + some old generation Regions together, aiming to keep pauses within -XX:MaxGCPauseMillis). Mixed GC is 'best effort' — it picks a subset of old Regions each round to meet pause targets. When the following happen, G1 can't hold on and degrades to single-threaded Full GC:
- Old generation occupancy exceeds the IHOP threshold (Initiating Heap Occupancy Percent, default 45%), starts concurrent marking, but after marking completes, Mixed GC reclamation speed can't keep up with object growth, old generation keeps rising until insufficient space;
- Humongous allocation failure: large object can't find enough contiguous space;
- Promotion failure: after Young GC, old generation can't hold promoted objects;
- Metaspace insufficient.
During Full GC, G1 degenerates to a single-threaded full-heap mark-compact similar to Serial, STW time is proportional to total live objects and heap size; 3-5 seconds for an 8GB heap, over ten seconds for a 32GB heap.
Why 'only-in, never-out' caches inevitably trigger Full GC
Objects in static Map are strongly referenced by GC Roots (static fields), eternally alive, and Young GC and Mixed GC can't touch them. The old Regions they occupy are marked as 'all live, zero reclaim' in Mixed GC, with near-zero reclamation efficiency. As the cache continues to grow, the old generation water level approaches the limit, Mixed GC can't digest it, the IHOP-triggered concurrent marking can't save it either, and it enters a Full GC vicious cycle: Full GC pauses a few seconds → cache grows again after recovery → another Full GC.
The core diagnostic idea is one sentence: find out who is stuffing objects into old generation, and who is holding heap memory. The former uses JFR allocation sampling, the latter uses jmap object histogram.
3. Hands-on: step-by-step code
Goal: reproduce the Full GC problem with Spring Boot 4.1.0 + JDK 21, then use jstat to detect the anomaly, JFR to find root cause, jmap to confirm the culprit, and finish with code fix and JVM parameter tuning. Each step's code can be copied and run directly.
3.1 Complete project: a 'leaky' report service
Create a Maven project. pom.xml uses Spring Boot 4.1.0 (the latest GA on Maven Central as of August 2026), Java version 21:
... (full pom as in original)
Configuration file application.yml:
server:
port: 8080
spring:
application:
name: gc-demo
Main class GcDemoApplication.java:
... (as in original)
The core 'leak source' ReportService.java — a Service that caches report data into a static Map, only in, never out:
... (as in original)
Controller ReportController.java:
... (as in original)
Start the app limiting heap to 512MB (for quick reproduction), plus GC logging and OOM dump parameters:
java -Xms512m -Xmx512m \
-XX:+UseG1GC \
-Xlog:gc*:file=/tmp/gc.log \
-XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=/tmp/ \
-jar target/gc-demo-1.0.0.jar
Then simulate business requests — generate a new report each day, call 40 times consecutively:
for i in $(seq 1 40); do curl -s "http://localhost:8080/report/2026-08-$(printf '%02d' $i)"; echo; sleep 1; done
40 * 20MB = 800MB, far exceeds the 512MB heap, Full GC will come quickly.
3.2 Diagnostic step 1: jstat detects the anomaly
jstat is a JDK built-in JVM statistics tool. jstat -gcutil flushes every second to show usage of each generation and GC counts/times. This is the first-hand evidence for locating Full GC. Find the process PID:
jps -l
Assume PID is 12345, flush every second to see each generation's water level:
jstat -gcutil 12345 1000
Output similar to:
S0 S1 E O M CCS YGC YGCT FGC FGCT CGC CGCT GCT
0.00 0.00 68.21 89.42 95.12 93.80 12 0.182 4 12.436 2 0.043 12.661
0.00 0.00 70.05 91.77 95.12 93.80 12 0.182 5 15.542 2 0.043 15.767
Key columns: O (old generation usage) consistently above 90%, FGC (Full GC count) rising, FGCT (Full GC total time) rising fast — 4 Full GCs took 12.4 seconds, averaging 3 seconds each. YGC only 12, so the problem is entirely not in young generation. Conclusion: Frequent Full GC, abnormal old generation water level, need to locate who occupies old generation.
3.3 Diagnostic step 2: JFR recording to find allocation hot spots
JFR (Java Flight Recorder) is a built-in sampling profiler since JDK 11+. Use jcmd with one line to record, no need to restart the app. It's the preferred tool for locating memory problems in production. Record for 60 seconds, continue pressing a few more requests during that time:
jcmd 12345 JFR.start name=fullgc duration=60s filename=/tmp/app.jfr
# Press a few more requests within 60 seconds to sample the problem code
for i in $(seq 41 45); do curl -s "http://localhost:8080/report/2026-08-$(printf '%02d' $i)"; echo; sleep 1; done
jcmd 12345 JFR.stop name=fullgc
JDK 14+ comes with the jfr command-line tool, directly view GC events and allocations:
jfr view gc app.jfr
jfr view allocation app.jfr
The allocation view lists the call stacks with the most memory allocation. You'll see new byte[20MB] in ReportService.generateReport standing out — the allocation hot spot points directly to the problem code, far more efficient than guessing.Note: JFR by default only retains the most recent 1 hour of rolling data. In production, recommend starting JFR without duration for continuous recording, and dump it out when problems occur.
3.4 Diagnostic step 3: jmap object histogram
jmap -histo lists the instance count and bytes occupied by each class of objects in the heap, used to confirm 'who is holding memory'; before deciding whether to dump the heap, look at this to save several GB of dump file transfer time. Execute:
jmap -histo:live 12345 | head -30
:live triggers a Full GC first then counts live objects. In output, [B (byte array) will dominate by far, taking hundreds of MB — matching JFR's conclusion: this 20MB large object plus static cache stuffed old generation.
If you want to see the reference chain (who references these arrays), dump the heap for MAT analysis:
jcmd 12345 GC.heap_dump /tmp/app.hprof
In MAT, run "Path to GC Roots" on [B, it will point all the way to the static field ReportService.REPORT_CACHE — root cause 100% confirmed.
3.5 Fix: solve 'only-in, never-out' at code level
The fix approach is to give the cache a limit and expiration: either cap the capacity, or periodically clear it, so objects in old generation can be reclaimed. Here, change to a 'clear every morning' version, zero extra dependencies, replace ReportService.java directly:
... (as in original)
computeIfAbsent is an atomic method of ConcurrentHashMap, no duplicate report generation under concurrency; scheduled clearing ensures cache lives at most 24 hours. If business requires long-term caching (e.g., non-reproducible data), switch to a local cache with capacity limit (e.g., Caffeine, set maximumSize + expireAfterWrite). The principle is the same: must give the cache an 'exit'.
3.6 Fix: JVM parameter tuning
After code fix, three things at JVM parameter level: align max heap and initial heap to avoid resize jitter, set G1 pause target, keep OOM snapshot. Note -Xmx and -XX:MaxRAMPercentage can't be used together; container environments recommend percentage form:
java -XX:InitialRAMPercentage=25.0 \
-XX:MaxRAMPercentage=50.0 \
-XX:+UseG1GC \
-XX:MaxGCPauseMillis=100 \
-XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=/logs/ \
-Xlog:gc*:file=/logs/gc.log:time,level,tags \
-jar gc-demo-1.0.0.jar
Parameter meanings:
| Parameter | Function |
|---|---|
-XX:InitialRAMPercentage=25.0 |
Initial heap is 25% of container memory, avoid frequent resizing after startup |
-XX:MaxRAMPercentage=50.0 |
Max heap is 50% of container memory, leaving room for metaspace and off-heap |
-XX:MaxGCPauseMillis=100 |
G1 pause target 100ms, Mixed GC controls each round's reclamation volume accordingly |
-XX:+HeapDumpOnOutOfMemoryError |
Auto-dump heap on OOM, preserve the scene |
-Xlog:gc* |
Unified logging switch since JDK 9+, replaces old -verbose:gc |
After fix, rerun load test: FGC count no longer grows, old generation water level fluctuates around 40%, interface P99 returns to tens of milliseconds — problem closed.
4. Pitfalls and best practices
The biggest pitfall in Full GC troubleshooting is 'tinker with parameters first': without locating root cause, increasing heap or lowering IHOP only drags Full GC from 'frequent' to 'more frequent'. The correct order is always: check code first, then tune parameters. Below are real pitfalls from production.
Pitfall 1: Increasing heap makes it even slower. Someone's first reaction to Full GC is to increase -Xmx from 2G to 8G. After heap grows, G1 Region becomes larger, Full GC serial compaction takes longer, pause goes from 1 second to 4 seconds; and if root cause is cache leak, a bigger heap gets filled up eventually. Heap size should be based on the 'live object set', not guesswork.First use jmap -histo to see how many live objects, then decide heap size.
Pitfall 2: Setting both -Xmx and -XX:MaxRAMPercentage simultaneously. Behavior is unpredictable when they conflict. Container environments (K8s/Docker) recommend using only percentage parameters to let JVM sense container memory limit; bare metal uses fixed values.Also note JDK 8u191+ enables UseContainerSupport by default; older JDKs in containers see host memory, another classic accident source.
Pitfall 3: Dumping heap directly, file of several GB can't transfer back. Online heap 8GB, dump becomes 6GB, transferring to local analysis takes half an hour. Correct posture: first use jmap -histo:live to see object histogram, locate if possible; when reference chain is necessary, first use JFR to see allocation stacks, then dump at last. Confirm disk space before dump, check df -h before GC.heap_dump.
Pitfall 4: Ignoring large objects (Humongous). Many people only focus on caches when investigating Full GC, forgetting objects larger than half a Region go directly to old generation in G1. Large arrays like byte[], int[] are 'old generation squatters' under G1. Even without cache leaks, frequently creating large arrays will make old generation skyrocket. When investigating, focus on array types like [B, [I, [C in jmap histogram.Business should prefer streaming and pagination over one-off large arrays.
Best practice checklist:
- Always include
-XX:+HeapDumpOnOutOfMemoryError+-XX:HeapDumpPath+-Xlog:gc*in startup parameters, so you have the scene when things go wrong; - Keep JFR always on in production (
jcmd <pid> JFR.start name=default settings=profile), JFR's CPU overhead is under 1%, far lower than the cost of fumbling after an incident; - Every cache must satisfy 'capacity limit + expiration time' at least one; static container caches are always code smells;
- Monitor GC: Prometheus + Micrometer collect
jvm_gc_pause_secondsandjvm_gc_overhead(GC time ratio), alert when GC overhead exceeds 10%, don't wait for Full GC to kill the service; - Re-run GC load tests after upgrading JDK version — different versions have very different G1 default parameters; old parameters may not apply.
5. Performance comparison and tech selection
Garbage collector selection in one sentence: choose Parallel for throughput, use G1 by default, use ZGC for large heap + ultra-low latency (sub-millisecond pauses); no collector can save leaking code. Comparison:
| Dimension | Parallel (JDK 8 default) | G1 (JDK 21 default) | ZGC |
|---|---|---|---|
| Goal | Max throughput | Balance throughput and pause | Extremely low latency |
| STW pause | Second-level (Full GC) | 10-200ms configurable | Sub-millisecond |
| Large heap (>16GB) performance | Poor | Good | Best |
| CPU overhead | Low | Medium | High (colored pointers + read barriers) |
| Use cases | Batch, offline jobs | Most online services | Large-heap online transactions, gaming |
G1 is the default collector in JDK 21; most Spring Boot services can stick with default, at most tune -XX:MaxGCPauseMillis. When to switch to ZGC? When heap exceeds 16GB and pause-sensitive (e.g., payment, transaction chains). JDK 21 introduced generational ZGC (JEP 439), enabled with -XX:+UseZGC -XX:+ZGenerational; generational mode balances low latency and throughput, much better than the initial JDK 15 version.But ZGC's CPU overhead is significantly higher than G1; switching to ZGC with a small heap is a loss.
The cure for Full GC isn't the collector, it's memory governance: caches have exits, large objects don't enter heap, batch data streamed. The collector is just the last line of defense.
6. Summary
The essence of frequent Full GC is runaway object survival rate. The troubleshooting order is fixed: jstat to see water level → JFR to see allocation hot spots → jmap to see object histogram → fix code → tune parameters. Every step has JDK built-in tools, no extra paid products required. Core conclusions condensed into four:
- Check code first, then tune parameters: static caches, large arrays, batch loading are the three culprits of Full GC;
jmap -histo:livecan confirm at a glance; - The tool chain is free: jps, jstat, jcmd, jfr, jmap all in JDK; JFR always-on costs under 1% CPU, the most worthwhile habit in production;
- Caches must have exits: capacity limit or expiration time, pick at least one. 'Only-in, never-out' caches inevitably trigger Full GC, just a matter of time;
- Parameter tuning is subtraction: MaxGCPauseMillis sets pause target, percentage sets heap size, HeapDumpOnOutOfMemoryError preserves scene. These three are enough; G1's other defaults are tuned for most scenarios.
Final reminder: collector selection (G1 vs ZGC) is icing on the cake; memory governance is the lifeline. Run through the troubleshooting flow in this article, and your service will be close to 'Full GC freedom'.