Java 21 Generational ZGC: Diagnosing Slow Product Search
Why do search results sometimes take two seconds? Understand temporary objects, GC pauses and Java 21 Generational ZGC, then investigate the real bottleneck.
Product-search example · Java 21 feature explained
“Why does searching for shoes sometimes take so long?”
Asha searches for running shoes. The product list takes two seconds to appear. The service creates temporary result objects, queries the catalogue and waits for inventory. We must identify which part causes the delay.
The problem we investigate
Unnecessary allocation can consume JVM resources. Some GC phases pause Java threads; allocation can also stall if reclamation cannot keep up. Database, inventory and CPU bottlenecks need separate evidence.
The Java 21 feature
Generational ZGC collects young objects separately from longer-lived ones, with most work concurrent. It can reduce allocation-stall risk compared with non-generational ZGC. It does not make an inventory service faster.
See the problem.
Understand the rule.
Java 21 Generational ZGC: Diagnosing Slow Product Search
A shopper waits for product search. Follow temporary objects, a 300 ms pause within a two-second search, and Java 21 Generational ZGC before validating real improvements.
Use the player controls to pause, seek, or enter fullscreen. The written explanation below is available at your own pace.
Open video separately ↗Follow one search request, then choose a justified change.
1. Search runs
Search shoes → Java service → catalogue query + inventory lookup → product summaries → response. Temporary objects become unreachable; live cache objects remain.
2. Compare the evidence
Match the request, GC pause, inventory span and CPU on the same JVM. A 300 ms pause does not explain a two-second search by itself.
3. Evaluate Java 21 Generational ZGC
Profile redundant allocation first. Compare the same search workload with G1 and generational ZGC; measure latency, errors, CPU and memory.
Investigate slow product search
Compare search duration, Java pauses and inventory-response waits. Then explore the young/old heap picture and the specific role of Java 21 Generational ZGC.
Open the product-search and GC lab ↗Archived: original checkout-based comparison
The previous example is preserved separately. The current article, lab and video use product search.
Open archived lab ↗1. Searching for shoes should not feel stuck
Asha types running shoes and waits for the results. The spinner keeps moving, then the page takes two seconds to respond. She tries again. The service might be waiting for inventory, running a slow query, competing for CPU, or doing memory-management work. A slow search alone does not tell us which one.
Our goal is clear: return correct product prices and availability promptly. This article, its narrated video and its interactive experiment use the same product-search example. All numbers are constructed teaching values, not measurements from this portfolio or a claimed production improvement.
2. What happens during a normal search?
Shopper → Java search service → catalogue database and inventory API → build result summaries → return the results.
Java creates objects while doing this work: product summaries, temporary strings and response buffers. The heap is the JVM-managed memory holding objects. After a response, many temporary objects become unreachable: the application no longer has a live path to them. Garbage collection, or GC, can reclaim that space for future work. Objects still reachable through a cache or another live reference must remain.
Think of clearing a workbench so the next job has room. Collection helps the service keep running; it does not make a slow inventory API answer faster. Some collector phases pause Java application threads, while other work runs concurrently. A JVM pause does not stop the separate inventory service.
3. What exactly does Java 21 add?
Generational ZGC, delivered in Java 21, separates young and older objects. Many short-lived search temporaries die young, so collecting young objects separately can avoid repeatedly processing the whole older population during young collections. Reachable young objects survive; old objects can also become garbage. Age is not the same as reachability.
ZGC performs most collection work concurrently with application work, with short stop-the-world phases. Generational ZGC aims to reduce allocation stalls and collection overhead compared with non-generational ZGC. That is a reason to evaluate it, not a promise of a particular search latency. G1 is also generational; GC, G1, ZGC and JFR were not all introduced in Java 21.
For JDK 21, explicitly enable it with:
java -XX:+UseZGC -XX:+ZGenerational -jar search-service.jarUse this exact version context: defaults and flags differ in later JDK releases. Check CPU capacity, heap headroom and your service's real workload before selecting a collector.
4. Two-second search does not mean a two-second GC pause
Open the interactive experiment. The article, video and default scenario show these same intervals on the same JVM:
| Evidence | Illustrative interval | Interpretation |
|---|---|---|
| Whole product search | 0–2,000 ms | Customer-facing server request duration |
| GC pause | 500–800 ms | 300 ms of overlapping pause evidence |
| Awaiting inventory response | 900–1,800 ms | 900 ms waiting for another system |
The pause is 300 ms, not 2,000 ms. These two disjoint intervals cover 1,200 ms; the rest needs more trace evidence. Coverage is not a causal attribution. If a pause lies inside an inventory wait, do not add it twice: the remote system may continue processing while Java is paused. Match timestamps and JVM instance IDs before comparing them.
Try Slow inventory service in the lab: there is no overlapping pause and a 1,800 ms inventory span. Collector flags cannot fix that remote delay. Try Pause inside an inventory wait to see why overlapping durations must not be double-counted.
5. How to see what the feature actually changes
Expand Java 21 Generational ZGC in the experiment. Before collection, there are six unreachable young temporaries, three reachable young result objects and three reachable older cache objects. Press Collect young generation: the six unreachable young objects become free space; the live objects remain. This deliberately simplified picture explains reachability and generations. It does not implement a JVM collector or predict a pause duration.
The positive improvement to investigate is less memory-management interference with search: fewer allocation stalls and acceptable tail latency while preserving results. The experiment does not fabricate a faster "after" number. A real comparison needs repeated equivalent workloads, the same limits and measured results.
6. First remove unnecessary allocation work
Use JFR allocation samples to find a real hotspot. For example, calculate a small stock summary directly instead of serializing the whole result set into an unused debug string on every request. Keep the actual response and prices unchanged.
import java.math.BigDecimal;
import java.util.List;
record Product(String sku, BigDecimal price, boolean available) {}
record SearchSummary(int matched, int available) {}
// Inside your search service class:
static SearchSummary summarize(List<Product> products) {
int available = 0;
for (Product product : products) {
if (product.available()) available++;
}
return new SearchSummary(products.size(), available);
}This Java 21-compatible method avoids an unnecessary intermediate collection for this summary; it still allocates the summary object. It is not a replacement for the result payload or a measured optimization. Bound page sizes and caches, preserve accurate price/availability semantics, and do not retain entire result histories accidentally. An unbounded cache retains reachable objects; switching collectors cannot make those objects safely disappear.
Download the standalone Java example and its executable correctness checks. Compile both with javac --release 21 and run java SearchAllocationTest. The checks cover counts, availability, unchanged prices, empty results and negative-price rejection; they do not benchmark GC.
7. Measure before and after under the same conditions
Capture request traces, GC logs and JFR on the correct instance. For a controlled recording:
java -XX:+UseZGC -XX:+ZGenerational \
-Xlog:gc*,safepoint:file=search-gc.log:time,uptime,level,tags \
-XX:StartFlightRecording=filename=search.jfr,duration=60s,settings=profile \
-jar search-service.jarIn Spring Boot, time the full search operation including failed attempts using Micrometer/Actuator, and correlate it with dependency spans. Use bounded labels such as outcome; do not use search terms, customer IDs or request IDs as metric tags. Protect JFR/log files because recordings can contain operational details.
Compare request p95/p99, throughput, timeouts/errors, allocation rate and stalls, pause distributions, CPU, process memory and post-GC live set. Keep dataset, concurrency, warm-up, CPU/memory limits and dependency behaviour equivalent. Test one variable at a time: allocation change first, then a collector comparison such as G1 versus Generational ZGC. Concurrent collection consumes CPU and needs headroom; a lower pause number alone is not sufficient evidence of a better service.
An average can hide unhappy shoppers: in an invented set of 100 requests, 98 at 200 ms and two at 2,000 ms give a mean of 236 ms and nearest-rank p99 of 2,000 ms. A server timer does not measure the entire browser experience.
8. What can still go wrong?
Slow database queries and inventory calls need their own fixes. CPU saturation can delay application and collector work. Retained objects can exhaust memory even with a good collector. Large result pages can create unnecessary allocation pressure. A small heap or constrained container can change the trade-offs. No overlapping pause does not prove GC consumes zero CPU.
Validate correctness as well as speed: the same query should return the expected products, prices and availability under load. Roll back a change that worsens errors, memory use or sustained throughput even if one latency percentile improves.
The original URL and archived checkout-based comparison remain available for continuity. The main explanation, new video and current diagnosis experiment all use product search.
Further reading
Keep exploring
Questions about these trade-offs or a topic for the next article?
Start a conversation ↗Share on LinkedIn ↗Join the conversation
Was this lesson helpful? Leave a like or share a question.
Comments
Related articles
Java Memory Leaks: Why a Cart Update Keeps Loading
Asha changes quantity from 1 to 2, but her cart keeps loading. Learn how abandoned cached copies can pressure the shared Java heap, and how a bounded cache protects current requests.
Java 21Java Deadlocks and Thread Dumps: Diagnosing Checkout That Stops Making Progress
The checkout spinner never finishes while CPU stays low; two workers may hold locks that each other needs.
Java 21Payment Idempotency in Spring Boot: Handling Timeouts and Retries
The gateway authorizes a payment but checkout never receives the response. Explore how stable keys, database uniqueness and reconciliation make retries safer.