Workbench / Volume 3 Exercises: The Backend
V3·41
Memory & Performance
Exercises for Volume 3, chapter 41: the performance workflow (measure, don't guess); stack versus heap, object layout, allocation and TLABs, escape analysis, boxing and strings; CPU caches, data layout and branch prediction; benchmarking with JMH; profiling with JFR, Mission Control and async-profiler; jcmd, jstack and jmap; finding memory leaks; tools in other languages; and a tuning checklist for JVM services. 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.
Start here: how this chapter's exercises work
The four sets and the locking work as before. Code is Java 21, with Python and Go for comparison. JMH couldn't be downloaded here, because Maven Central was blocked by this environment's network policy. So JMH appears as setup and expected results, and every other quoted output is a real measurement.
Five of the real measurements catch experienced developers:
- P2. Summing the values ≥ 128 in 20 million ints took 81.7 ms in random order and 16.1 ms when sorted. Same data, same work; the difference is branch prediction.
- P3. 100,000 disabled debug log calls built their message string and called
expensive()100,000 times. With theSupplierform, it was called 0 times. - P4. Adding 1 million elements to a default
ArrayListallocated 14.6 MB. A presized one allocated 4.0 MB. - P6. A leaking audit cache showed up in
jcmd GC.class_histogramas 1.2 millionbyte[](337 MB), 600,000HashMap$Nodeand 600,001OrderDto. JFR's allocation samples pointed atbyte[]. - P7. 2 million duplicate kitchen-name strings used 135 MB of heap. With
-XX:+UseStringDeduplicationthey used 58 MB, and afterintern()24 MB.
The chapter's lab covered these, and the exercises build on them rather than repeat them:
- row-by-row against column-by-column traversal: 14.9 ms against 256.8 ms;
- shuffled object arrays against
double[]: 84.1 ms against 6.2 ms; - escape analysis on and off: 0 against 60 GCs;
- a benchmark loop deleted as dead code: 0.0 ms.
Coverage map.
| Chapter component | Exercises |
|---|---|
| the performance workflow | T1, P1 |
| stack vs heap; object layout; references | T2, P5 |
| allocation and TLABs; escape analysis | T3, P4 |
| boxing and unboxing | T3, P5 |
| strings: interning, deduplication, allocation | T4, P7 |
| CPU caches; data layout; branch prediction | T5, P2 |
| benchmarking with JMH | T6, P1 |
| profiling: CPU, allocation, locks, wall-clock | T7, P8 |
| JFR and Mission Control; async-profiler | T7, P6, P8 |
| jcmd, jstack, jmap, VisualVM | T8, P6 |
| finding a memory leak | T8, P6 |
| tools in other languages | T9, P9 |
| logging and other hidden costs | T4, P3 |
| tuning checklist | T9, S1 |
Theory
T1. The performance workflow
- State the workflow:
- define the goal as an SLO (p99 latency, throughput, cost);
- reproduce under realistic load;
- measure and profile;
- form a hypothesis;
- change one thing;
- measure again;
- keep the change or revert it.
Why does "optimise what you think is slow" fail? Use the lab's dead-code loop (0.0 ms) and P2's branch-prediction result as examples of intuition misleading. 2. Explain Amdahl's law with a TiffinBox request. It spends 70% of its time in the database, 20% in JSON and 10% in pricing. What's the maximum overall speed-up from making pricing 10× faster? From making the database 2× faster? 3. Distinguish latency from throughput, average from percentiles, and why you must use percentiles and histograms (HdrHistogram) rather than averages. Explain coordinated omission in load tests, and why "the server handled 1,000 req/s" means little without the latency at that rate.
T2. Where data lives: stack, heap, layout and references
- What lives on the stack (primitive locals, references, frames) and what lives on the heap (all objects, arrays)? Explain why Java has no "stack-allocated objects" in the language, while escape analysis gives some of the effect (the lab: 0 GCs; ch40's P4: 0 bytes).
- Recap object layout (ch40's T4: 12-byte headers, or 8 compact; 8-byte alignment; compressed oops) and estimate the footprint of:
- a
record Line(String dish, int qty, long paise)with a 10-character Latin-1 dish name; - anArrayListof 1,000 such lines; - aHashMap<String, Line>of 1,000 lines.
Then explain "shallow" and "retained" size.
3. Explain the difference between references and values for performance. The lab's array of objects took 84.1 ms against 6.2 ms for double[]. How do "structure of arrays" layouts, primitive collections and Valhalla's value classes help?
T3. Allocation, TLABs, escape analysis and boxing
- Explain allocation in HotSpot: - TLABs (thread-local allocation buffers): bump-pointer allocation without locks, typically ~10 ns; - young-generation (Eden) collection: cost proportional to the live data; - why allocating short-lived objects is cheap and keeping them alive is expensive; - the lab's remark about object pooling: don't pool small objects.
- P4 found that the default
ArrayListallocated 14.6 MB for 1 million adds, against 4.0 MB presized; theStringBuilderallocated 1.2 MB for 100,000 appends. Explain where each byte comes from (growth copies, boxedIntegers, though values 0–99 are cached; theObject[]itself). When is presizing worth it? - Boxing. Recap ch33's lab (
List<Integer>18.7 ms againstint[]5.7 ms), ch37's (Stream<Integer>595.6 ms againstIntStream6.8 ms) and ch35's (74 bytes per map entry). List the places boxing hides: collections, generic methods,Map<String, Integer>counters, varargsObject..., logging parameters,Optional<Integer>, and lambdas over boxed functional interfaces.
T4. Strings, logging and other hidden costs
- Strings. Cover:
- compact strings (Latin-1
byte[]since JDK 9); -intern()and the string table; - G1/ZGC string deduplication (-XX:+UseStringDeduplication), which shares thebyte[]of equal strings and leaves theStringobjects distinct. P7: 135 MB → 58 MB. - Intern-based sharing (P7: 24 MB), which removes duplicateStringobjects too.
When do duplicate strings become a real problem (deserialising millions of rows with repeated values: kitchen names, statuses, cities)? What's the best fix (enums, ids, intern or a canonicalising map at the parser)?
2. Logging costs. P3: with debug disabled, log.fine("order " + i + " details " + expensive()) still built the string and called expensive() 100,000 times, while log.fine(() -> …) called it 0 times. Explain parameterised logging (log.debug("order {}", id) in SLF4J), its remaining costs (varargs arrays, boxing), the isDebugEnabled guard, and synchronous against asynchronous appenders.
3. Other hidden costs in backend hot paths:
- exceptions as control flow (ch33's lab: 67 ms against 1.7 ms);
- regex compilation per call (String.matches, split with a regex);
- String.format in loops;
- reflection-heavy mapping;
- SimpleDateFormat creation;
- creating ObjectMapper per request;
- opening connections per request.
For each, give the fix.
T5. CPU caches, data layout and branch prediction
- Recap the memory hierarchy: L1 (~1 ns), L2 (~4 ns), L3 (~10–20 ns), DRAM (~100 ns), with 64-byte cache lines and hardware prefetchers. The lab's row-against-column traversal of the same data took 14.9 ms against 256.8 ms (17×). Derive why.
- Branch prediction. P2's sum of values ≥ 128 took 81.7 ms for random data and 16.1 ms for sorted data. Explain the misprediction penalty (~15–20 cycles), why sorted data makes the branch predictable, and why the JIT sometimes removes the difference with a conditional move or vectorisation (so results vary by JVM and CPU). Write a branchless version.
- When do these hardware effects matter in a backend, and when are they noise? Compare a request that does 3 database calls with an in-memory recommendation scorer over 1 million dishes, a JSON parser, and a rate limiter's hot counter (false sharing, ch38's P8).
T6. Benchmarking with JMH
- Why do hand-written benchmarks lie? - dead-code elimination (the lab: 0.0 ms); - constant folding; - missing warm-up (ch40: 8.1 ms down to 0.9 ms); - profile pollution between tests in one JVM (ch40's P5); - GC noise; - loop unrolling and hoisting; - timer resolution; - measuring the setup rather than the work.
How does JMH address each (forks, warm-up, Blackhole, @State, @Setup levels, @OperationsPerInvocation, statistics)?
2. Write the JMH benchmark comparing Stream<Integer>, IntStream and a loop (ch37's lab), with sensible annotations, and the profilers you'd attach (-prof gc for allocation, -prof perfasm or -prof async for hot code). What output would you expect?
3. Microbenchmarks against macrobenchmarks. When should a team use JMH (library code, algorithms, a hot loop identified by profiling), and when a load test (k6, Gatling) against a deployed service? Why is a 10% JMH win often invisible in production?
T7. Profiling: CPU, allocation, locks and wall-clock
- Name the four profile types and what each answers: - CPU: where is CPU spent? - allocation: what allocates the most bytes? - lock and monitor contention: where do threads wait for locks? - wall-clock: where do threads spend real time, including I/O and sleeps?
Why is a CPU profile misleading for an I/O-bound request (ch38)?
2. Compare JFR with JMC and async-profiler:
- overhead (JFR's default ~1%; profile settings a bit more);
- safepoint bias in older sampling profilers (JFR and async-profiler avoid it);
- flame graphs;
- native frames;
- allocation sampling (P6's 438 byte[] samples);
- continuous production use.
How do you read a flame graph (width is time; look for wide plateaus)?
3. Profiling in containers and Kubernetes: jcmd JFR.start through kubectl exec, continuous profiling services (Pyroscope, Datadog, Grafana), the security of attaching agents, and what to capture during an incident.
T8. Finding a memory leak and the command-line tools
- Define a Java memory leak: objects that are no longer needed but remain reachable. Common sources:
- unbounded caches (P6's
AUDITmap); - listeners never removed; -ThreadLocals (ch38's P4); - class-loader leaks (ch40's P3); - static collections; - unclosed resources holding buffers; -String.substringsharing (historical, before 7u6).
What are the symptoms in metrics (the live set rising after GC, more frequent Full GCs, finally OOM)?
2. Walk through P6's investigation:
1. jcmd <pid> GC.class_histogram showed 1,215,927 byte[] (336.9 MB), 602,710 HashMap$Node, 600,001 L$OrderDto and 614,929 String;
2. JFR allocation samples were dominated by byte[] (438 of 498);
3. a heap dump in Eclipse MAT's dominator tree would show the AUDIT map's retained size and its path to GC roots.
Then explain the fix (a bounded cache with expiry: Caffeine, ch53) and the regression test.
3. Know the tools:
- jcmd (one entry point: Thread.print, GC.heap_info, GC.class_histogram, GC.heap_dump, VM.native_memory, JFR.*, VM.flags);
- jstack, jmap and jstat (legacy, but still useful);
- VisualVM and JConsole (JMX GUIs);
- jfr (the command-line JFR reader);
- heap-dump analysers (Eclipse MAT, VisualVM).
Which are safe in production, and which pause the JVM for long?
T9. Other languages' tools and the tuning checklist
- Map the tools across ecosystems:
- Go:
pprof(CPU, heap, goroutine, block and mutex profiles;net/http/pprof),go test -benchwith-benchmem, thetracetool. - Python:cProfile, py-spy (sampling, no code change),tracemalloc. P9's tracemalloc attributed 58.2 MiB in 799,986 allocations to the line building the cache. - Node:--cpu-prof,--heap-prof, Chrome DevTools, clinic.js. - Rust:perf, flamegraph, criterion for benchmarks. - .NET: dotnet-trace and dotnet-counters.
What's common to all of them? 2. Write the tuning checklist for a JVM service, in order: 1. the SLO and load test; 2. traces and the I/O share (database, network); 3. CPU and allocation profiles; 4. GC logs and the live set; 5. heap sizing and container headroom; 6. thread pools and concurrency limits (ch38); 7. connection pools (ch49); 8. caching (ch53); 9. code-level fixes (boxing, regex, logging, layout); 10. JVM flags last.
Justify the order. 3. What does "performance budget" mean for a team, and how do you prevent regressions (performance tests in CI with thresholds, dashboards per release, budgets per endpoint)?
Programming exercises
P1. A benchmark that lies, and the JMH version
Write a hand-timed benchmark of "parse 1 million quantities with Integer.parseInt" whose result is discarded, and observe the near-zero time (dead-code elimination, as in the lab). Fix it by using the result, then by warming up. Then write the JMH version (with @State, @Setup, warm-up, forks, and Blackhole) and list the -prof gc columns you'd read.
P2. Branch prediction and data layout
Measure the sum of values ≥ 128 over 20 million random ints, then over the same data sorted, after warm-up. Then:
- write the branchless version and measure both orders;
- reproduce the lab's row-against-column traversal;
- compare an array of shuffled Point objects with two double[] arrays for a "distance from kitchen" scan over 5 million points.
P3. Hidden costs: logging, regex and formatting
Measure 100,000 disabled debug logs three ways: eager concatenation, the Supplier form, and the isLoggable guard. Count the calls to an expensive() argument. Then measure:
- String.matches(regex) against a precompiled Pattern;
- split(",") against split("[,;]");
- String.format against StringBuilder in a loop of 1 million.
Report the results and the fixes.
P4. Allocation measurement and presizing
Using ThreadMXBean.getThreadAllocatedBytes, measure the bytes allocated by:
- a default against a presized ArrayList of 1 million;
- a HashMap of 1 million with and without an initial capacity;
- a StringBuilder building 500 KB;
- Collectors.toMap over 1 million records against a presized map.
Then find the allocation hot spot in a TiffinBox report job with JFR allocation sampling.
P5. Footprint estimation and verification
Estimate the footprint of TiffinBox's in-memory menu cache: 50,000 dishes as records with 5 fields (long id, String name, String kitchen, long paise, EnumSet<Dietary>) in a HashMap<Long, Dish>. Then verify it with a heap histogram, or JOL if it's available (org.openjdk.jol). Then shrink the footprint:
- canonical kitchen strings;
- DishId as a primitive key in a primitive map;
- an enum bit mask instead of EnumSet.
Report the before and after sizes.
P6. Find a memory leak
Run a service simulation that leaks through a static "audit" map. Use:
- jcmd GC.class_histogram (twice, minutes apart);
- JFR allocation sampling;
- a heap dump analysed in Eclipse MAT (dominator tree, path to GC roots).
Fix the leak with a bounded Caffeine cache, and write a regression test that fails on unbounded growth.
P7. Duplicate strings: deduplication against interning
Create 2 million strings with 3 distinct values (kitchen names) as separate String objects. Measure the heap after GC by default, with -XX:+UseStringDeduplication, and after interning. Then parse a 1-million-row CSV of orders, canonicalising kitchen names and statuses at the parser (enum for status, a Map for kitchens), and compare the memory with naive parsing.
P8. Profile a slow endpoint
Build a small HTTP endpoint (the JDK's HttpServer, or Spring if you have it) that:
- serialises 1,000 orders to JSON;
- uses String.format for money;
- compiles a regex per request;
- logs eagerly at debug.
Load it at a fixed arrival rate, record JFR with profile settings (and async-profiler if available), and identify the top three CPU and allocation sites. Fix them one at a time, measuring p99 after each.
P9. Profiling tools in Python and Go
In Python, find the line allocating the most memory with tracemalloc, and the slowest function with cProfile (or py-spy). In Go, expose net/http/pprof, capture a 30 s CPU profile and a heap profile under load, and read the top functions with go tool pprof -top. Then write a benchmark with testing.B and -benchmem.
Cumulative projects (chapters so far: Volume 1, Volume 2, and Volume 3's 33–41)
C1. A performance budget and regression gate for TiffinBox
Define performance budgets for the three critical endpoints (menu, checkout, order status): p99 latency, CPU per request and allocation per request. Build: - a k6 load test at a fixed arrival rate with thresholds; - JMH benchmarks for the pricing core (ch37's C1) and JSON serialisation of the order view; - a CI job running both nightly, failing on regression beyond 10%; - a dashboard comparing releases.
Seed a regression (a regex compiled per call in pricing) and show that the gate catches it.
Combines: Volume 2's frontend performance budgets (ch27), ch37's pure pricing core, ch38's concurrency settings, ch40's JVM metrics, and this chapter.
C2. Memory diet for the kitchen dashboard service
The kitchen dashboard service (ch35's C1, ch38's C2) holds 500,000 orders in memory and uses 3 GB of heap. Profile the live set and reduce it by at least 50% without changing behaviour. Use: - canonical strings or enums; - primitive ids; - compact records; - removing duplicate indexes; - snapshot sharing; - compact object headers on JDK 25.
Report the per-step savings and the GC behaviour (pause p99, GC CPU) before and after.
Combines: ch33's types, ch35's collection memory, ch38's snapshot design, ch39's compact headers, ch40's object layout, and this chapter.
C3. A cross-runtime profiling exercise
Take the same small workload (parse 100,000 JSON orders, compute totals, serialise a summary) in Java, Go, Python and Node. For each runtime: - profile CPU and allocation with the native tool; - find the top cost; - apply one idiomatic fix; - report the before and after times.
Compare what the top cost was in each language and why.
Combines: Volume 2's Node tooling, ch33's language comparison, ch40's runtime differences, and this chapter's tools.
What the chapter leaves out
Load testing methodology in depth
Good load tests need: - realistic data (production-like distributions of cart sizes, kitchens, hot keys); - a realistic arrival process (open model, bursts); - warmed caches and JVMs; - the same infrastructure as production (CPU limits, network, database size); - long enough runs to see GC and leaks (soak tests).
Gatling, k6, wrk2 and Locust are the common tools. Treat test environments as production-like, or results mislead. Ch54 covers testing.
Kernel and OS-level performance
perf, eBPF tools (bcc, bpftrace), and Brendan Gregg's USE method (utilisation, saturation, errors per resource) diagnose problems below the JVM: CPU throttling from container CPU quotas (CFS throttling causing latency spikes), network retransmits, disk I/O waits, NUMA effects, and page faults. Kubernetes CPU limits in particular cause p99 spikes when containers exceed their quota within a scheduling period. Measure throttling metrics.
Database and network performance
For most backends, the largest wins are outside the JVM:
- indexes and query plans (EXPLAIN ANALYZE);
- N+1 queries;
- connection pool sizing;
- batching;
- payload sizes and compression;
- HTTP/2 or HTTP/3 connection reuse;
- caching.
Ch49 (persistence), ch53 (caching) and Volume 4 (databases) cover these. Always check traces before profiling the JVM.
Native image and AOT performance characteristics
GraalVM native images have different profiles: Serial GC by default (G1 in Oracle GraalVM), no JIT warm-up but lower peak without PGO, and smaller memory. Profiling them uses perf and native tools rather than JFR (JFR is partially supported). If you deploy native images (ch42), your performance tooling must change too.
Statistics for performance results
Benchmark results are samples with variance. Report confidence intervals (JMH does), use enough iterations and forks, compare distributions rather than single numbers, and beware of multiple comparisons. A 3% "win" inside the noise isn't a win. For load tests, compare percentiles across several runs, and use canary analysis with statistical tests (Kayenta-style) in production rollouts.
Senior exercises
S1. The performance engineering standard for the team
Write a one-page standard covering: - SLOs and budgets per endpoint; - the required load test before major releases; - profiling tools available in every environment (JFR continuous, async-profiler); - the rules for JMH benchmarks; - the review checklist for hot-path code (boxing, regex, logging, allocation in loops, layout); - the order of the tuning checklist (T9); - who owns performance regressions.
Tie each item to an output from this chapter.
S2. Review a performance optimisation pull request
A PR "optimises" the order service by:
- adding an object pool for OrderDto objects;
- replacing List<Line> with Line[] everywhere;
- caching every findById result in a static HashMap;
- using String.intern() on every JSON string field;
- adding -XX:+AlwaysPreTouch -XX:+UseLargePages.
It includes a hand-timed benchmark showing a 40% improvement. Write the review.
S3. Decide whether to rewrite a hot service in Go or Rust
The menu service handles 5,000 req/s across 12 JVM instances. A team proposes rewriting it in Rust to cut cost, citing lower memory and no GC. Profiling shows: - 45% of CPU in JSON serialisation; - 20% in a regex-based search filter; - 15% in GC; - the rest in framework code.
Decide, with a cost and risk analysis, and propose the alternative path.
S4. Teach "measure, don't guess" with five outputs
Prepare a 20-minute session using: - the lab's dead-code loop (0.0 ms); - P2's branch prediction (81.7 against 16.1 ms); - the lab's traversal order (17×); - P3's disabled-debug-log cost (100,000 calls); - P6's leak histogram.
For each, take a prediction, reveal, explain, and give the tool that would have found it.
S5. Plan a cost-reduction initiative for the JVM fleet
TiffinBox's cloud bill for compute is rising. 40 JVM services run with generous CPU and memory requests set years ago. Plan a 3-month initiative to cut compute cost by 30% without hurting SLOs. Cover:
- the measurement baseline;
- right-sizing requests and limits;
- JVM settings (MaxRAMPercentage, GC, compact headers, AOT caches);
- autoscaling;
- the top-N hot-spot fixes;
- the guardrails;
- reporting.