SD·194B
Java and Spring at L5/L6
What design- and production-level depth in Java and Spring looks like, with experiments run on JDK 21: level ladders; the Java Memory Model shown by a reader thread that never sees a plain write, and the same visibility rules in C, C++, Go, Rust and Zig; the JVM's memory, JIT and garbage collectors, with nine measured runs comparing Parallel, G1 and generational ZGC under allocation pressure; virtual threads versus a platform pool (581 ms → 156 ms) and synchronized pinning on JDK 21 (515 ms vs 11 ms); the L4 toolkit (jcmd, JFR, async-profiler, heap and thread dumps) and failure signatures; Spring's container, proxies and why self-invocation silently skips @Transactional (reproduced with a JDK proxy); transactions, JPA pitfalls, Spring MVC vs WebFlux vs virtual threads; and production concerns: containers, startup, upgrades and Spring Boot 4.
Start here: what L5/L6 Java and Spring look like
At L2 you can build a Spring Boot service. At L5/L6 you can say why it behaves as it does under load, choose its concurrency model, find the cause of a latency spike in a heap dump or a GC log, and run it through upgrades and incidents. This chapter walks the ladder for Java and Spring and the internals that separate the levels: the Java Memory Model, the JVM's garbage collectors and JIT, virtual threads, Spring's proxies and transactions.
One example of the gap between L2 and L4
Java 21's virtual threads let you write simple blocking code and still handle thousands of concurrent requests. The lab ran 10,000 tasks that each block for 100 ms (like an HTTP or database call):
| Executor | Time |
|---|---|
| pool of 200 platform threads | 5.15 s |
| pool of 2,000 platform threads | 0.76 s |
| a virtual thread per task | 0.27 s |
An L2 engineer stops there and switches everything to virtual threads. An L4 engineer knows the catch: on Java 21, a virtual thread that blocks inside a synchronized block pins its carrier thread. With 2 carriers, 2,000 such tasks took 100 s, versus 0.11 s with a ReentrantLock. (Java 24 removed most of this pinning; knowing which JDK you run is part of L4.) The L5 question is then "should this service use virtual threads at all, given its libraries, locks and connection pools?" and the L6 question is "how do we roll it out and know it worked?"
How deep to go in Java and Spring
Volume 17 defines six mastery levels; for this chapter's topics they look like this:
| Level | You can… |
|---|---|
| L1 | name the JVM's parts, Spring's core ideas and Java's concurrency options |
| L2 | build and test a Spring Boot service with data access and transactions |
| L3 | explain the memory model, GC, JIT, virtual threads and Spring proxies |
| L4 | diagnose leaks, GC pauses, contention, pinning and transaction bugs with JFR, dumps and logs |
| L5 | choose concurrency models, GC settings, data-access patterns and framework features for a system |
| L6 | run JVM fleets through upgrades, incidents and cost/capacity planning |
Java: the ladder
| Level | Observable behaviour |
|---|---|
| L1 | Knows Java is a statically typed, garbage-collected language on the JVM; knows the core library areas |
| L2 | Writes idiomatic modern Java: records, sealed types, switch patterns, streams, Optional used sensibly, try-with-resources, collections chosen correctly, unit tests |
| L3 | Explains the JVM: class loading, bytecode, interpreter and tiered JIT, object layout, heap generations, how each collector works, the Java Memory Model's happens-before rules, how synchronized, volatile and java.util.concurrent are implemented |
| L4 | Diagnoses with tools: reads GC logs, thread dumps, heap dumps, JFR recordings and flame graphs; finds leaks, contention, deadlocks, allocation hot spots, JIT deoptimisations |
| L5 | Chooses: collector and heap sizing for a latency target; virtual threads vs pools vs reactive; data structures for memory footprint; JDK version strategy; when Java isn't the right tool |
| L6 | Operates JVM services in containers at scale: memory budgets, startup and warm-up, JDK upgrades across a fleet, security (deserialisation, dependency CVEs), cost per request |
The Java Memory Model, seen
L3 starts with this question: when one thread writes a field, when does another thread see it? The Java Memory Model (JLS chapter 17) answers: only when there's a happens-before relationship between the write and the read, created by things like a volatile write followed by a read of the same variable, unlocking then locking the same monitor, Thread.start(), Thread.join(), and the java.util.concurrent classes. Without one, the JIT and the CPU may reorder, cache in registers, or hoist reads out of loops, all legally.
// The Java Memory Model in one experiment: a plain field written by one thread may never be seen by another.
public class Jmm {
static boolean plainStop = false;
static volatile boolean volatileStop = false;
public static void main(String[] args) throws Exception {
Thread plain = new Thread(() -> { long spins = 0; while (!plainStop) spins++; System.out.println("plain reader saw the write after " + spins + " spins"); });
Thread vol = new Thread(() -> { long spins = 0; while (!volatileStop) spins++; System.out.println("volatile reader saw the write"); });
plain.setDaemon(true); vol.setDaemon(true);
plain.start(); vol.start();
Thread.sleep(500); // let the JIT compile the hot loops
plainStop = true; volatileStop = true;
vol.join(2000); plain.join(2000);
System.out.println("plain reader still running after 2 s: " + plain.isAlive());
System.out.println("volatile reader still running after 2 s: " + vol.isAlive());
}
}
volatile reader saw the write
plain reader still running after 2 s: true
volatile reader still running after 2 s: false
The C2 compiler hoisted the read of plainStop out of the loop (it's not volatile and nothing in the loop creates a happens-before edge, so reading it once is a legal optimisation): the loop runs forever. This is not a theoretical concern: it is how "works on my machine, hangs in production under load" bugs happen.
Every systems language has the same problem and a different contract:
// Java: volatile (or AtomicBoolean) creates happens-before between the write and later reads
static volatile boolean stop;
// writer: stop = true; reader: while (!stop) { ... }
// C11: a data race on a plain variable is undefined behaviour; use _Atomic with an explicit memory order
#include <stdatomic.h>
#include <stdbool.h>
static atomic_bool stop = false;
void writer(void) { atomic_store_explicit(&stop, true, memory_order_release); }
void reader(void) { while (!atomic_load_explicit(&stop, memory_order_acquire)) { /* work */ } }
// C++11+: same model as C11; std::atomic defaults to sequential consistency
#include <atomic>
std::atomic<bool> stop{false};
void writer() { stop.store(true, std::memory_order_release); }
void reader() { while (!stop.load(std::memory_order_acquire)) { /* work */ } }
// Go: the memory model (revised 2022) makes racy programs' behaviour limited but wrong; use sync/atomic or channels
package main
import "sync/atomic"
var stop atomic.Bool
func writer() { stop.Store(true) }
func reader() {
for !stop.Load() {
// work
}
}
// `go test -race` / `go run -race` detects unsynchronised access at runtime.
// Rust: a plain `static mut` read/write across threads needs `unsafe`; safe code must use atomics or locks.
// The compiler enforces this through the Send and Sync traits — the data race doesn't compile.
use std::sync::atomic::{AtomicBool, Ordering};
static STOP: AtomicBool = AtomicBool::new(false);
pub fn writer() { STOP.store(true, Ordering::Release); }
pub fn reader() { while !STOP.load(Ordering::Acquire) { /* work */ } }
// Zig: std.atomic.Value with explicit orderings (Zig 0.14+)
const std = @import("std");
var stop = std.atomic.Value(bool).init(false);
pub fn writer() void { stop.store(true, .release); }
pub fn reader() void { while (!stop.load(.acquire)) {} }
The L3 point across languages: atomics define ordering, not just atomicity. Release/acquire pairs say "everything written before the release is visible after the acquire". Java's volatile is roughly sequentially consistent (stronger than acquire/release); VarHandle exposes weaker modes (setRelease, getAcquire, getOpaque) for the rare cases that need them.
The JVM's moving parts
- Class loading and linking: classes load lazily on first use through a delegation hierarchy (bootstrap → platform → application loaders); static initialisers run once, under a lock (a slow static initialiser blocks every thread touching the class).
- Execution: bytecode is interpreted, profiled, then compiled by C1 (fast, lightly optimised) and C2 (slow, aggressively optimised using profile data: inlining, escape analysis, loop unrolling, speculative devirtualisation). Speculation that turns out wrong triggers deoptimisation back to the interpreter. Hence warm-up: a service is slow for its first thousands of requests.
- Object layout: a 12-byte header (mark word + compressed class pointer) on 64-bit JVMs with compressed pointers, fields, padding to 8 bytes. A
Longis 24 bytes (12-byte header + 8-byte value, padded to 8) plus a 4-byte reference to it; aHashMapentry is about 32 bytes plus key and value objects. Primitive arrays and records of primitives are dense; boxed collections are not. (Project Valhalla's value classes aim to change this.) - Escape analysis: objects that don't escape a compiled method can be scalar-replaced (never allocated on the heap).
- Garbage collection: generational hypothesis (most objects die young). Young collections copy live objects from Eden to survivor spaces; survivors are promoted to the old generation.
| Collector | Design | Pauses | Throughput | Choose when |
|---|---|---|---|---|
| Serial | Single-threaded, stop-the-world | Long | OK for tiny heaps | ≤ 1 CPU, small heap containers |
| Parallel | Multi-threaded, stop-the-world | Long, proportional to live old-gen data | Highest | Batch jobs where only total time matters |
| G1 (default) | Regions; concurrent marking; incremental evacuation targeting a pause goal (MaxGCPauseMillis, default 200 ms) |
Short, usually ≤ tens of ms | High | Most services |
| ZGC (generational since JDK 21; non-generational removed in JDK 23) | Concurrent relocation with load barriers and coloured pointers | Sub-millisecond GC pauses, independent of heap size | Lower (barrier cost, concurrent CPU) | Large heaps, strict tail latency, spare CPU |
| Shenandoah | Concurrent compaction with barriers | Sub-ms to ms | Lower | Similar to ZGC (Red Hat builds and others) |
Measuring collectors (and why L5 means measuring)
A workload with a 1.5 GB live set in a 3 GB heap, churning the old generation while allocating short-lived garbage, timing each loop iteration as the application sees it (pauses plus allocation stalls), three runs each on a 2-core sandbox, JDK 21:
// Application-observed pauses under allocation pressure with a large live set: compare collectors.
List<byte[]> live = new ArrayList<>();
for (int i = 0; i < 1500; i++) live.add(new byte[1 << 20]); // ~1.5 GB live set
// loop for 8 s: allocate 64 × 16 KB garbage, replace one 1 MB live array, record iteration time
Parallel run 1 iterations=9,135 p50=0.31 ms p99.9=163.75 ms max=1401.5 ms
G1 run 1 iterations=17,878 p50=0.27 ms p99.9=7.32 ms max=16.0 ms
ZGC run 1 iterations=2,373 p50=0.44 ms p99.9=27.32 ms max=41.3 ms
Parallel run 2 iterations=10,491 p50=0.31 ms p99.9=168.57 ms max=311.2 ms
G1 run 2 iterations=14,920 p50=0.31 ms p99.9=9.56 ms max=43.0 ms
ZGC run 2 iterations=1,878 p50=0.54 ms p99.9=59.01 ms max=128.5 ms
Parallel run 3 iterations=11,048 p50=0.28 ms p99.9=159.65 ms max=323.4 ms
G1 run 3 iterations=17,455 p50=0.28 ms p99.9=7.10 ms max=117.8 ms
ZGC run 3 iterations=606 p50=14.28 ms p99.9=35.52 ms max=35.5 ms
Parallel shows its full-collection pauses (up to 1.4 s). G1 holds p99.9 under 10 ms here. ZGC, the "low-latency" collector, did worse than G1 in this setup, and its GC log shows why: allocation stalls (hundreds of "Allocation Stall" entries), where application threads wait because the concurrent collector can't keep up. ZGC's pauses are tiny, but it needs CPU for its concurrent threads (2 cores is starved) and heap headroom (live set at 50% of heap is tight). On a 16-core machine with a 3–4× heap/live ratio the ranking typically flips. That's the L5 lesson: collector choice depends on hardware, heap headroom and allocation rate, and the only reliable answer is a measurement on the target environment with application-level latency, not GC pause logs alone.
Virtual threads
Java 21's virtual threads (JEP 444) are lightweight threads scheduled by the JVM onto a small pool of carrier platform threads. When a virtual thread blocks on I/O or sleep, it unmounts from its carrier, freeing it. This gives the throughput of asynchronous code with the simple thread-per-request style.
// 10,000 tasks that each block 10 ms
run(Executors.newFixedThreadPool(200), n, Vt::sleep10); // platform threads
run(Executors.newVirtualThreadPerTaskExecutor(), n, Vt::sleep10); // virtual threads
// Pinning on JDK 21–23: blocking inside synchronized keeps the carrier busy (4 carriers configured)
synchronized (mon) { sleep10(); } // 200 tasks, distinct monitors
l.lock(); try { sleep10(); } finally { l.unlock(); } // 200 tasks, distinct ReentrantLocks
platform pool of 200, 10000 tasks x 10 ms sleep: 581 ms
virtual thread per task, 10000 tasks x 10 ms sleep: 156 ms
virtual, sleep inside synchronized (200 distinct monitors): 515 ms
virtual, sleep inside ReentrantLock (200 distinct locks): 11 ms
carrier threads: 4
The pool is bounded by 200 threads (10,000 × 10 ms / 200 ≈ 500 ms plus overhead); virtual threads run all 10,000 concurrently. The pinning rows show L3 knowledge you need for L5 decisions: on JDK 21, a virtual thread that blocks inside synchronized can't unmount, so with 4 carriers the 200 tasks run 4 at a time (200 / 4 × 10 ms ≈ 500 ms); with ReentrantLock they unmount and all overlap. JDK 24 (JEP 491) removed this pinning for synchronized, so on 24+ (including JDK 25 LTS) both rows behave alike; native frames and some class-initialisation cases still pin. -Djdk.tracePinnedThreads (21–23) or the JFR event jdk.VirtualThreadPinned finds pinning.
L5 choices with virtual threads:
- They help I/O-bound concurrency (many requests waiting on databases and HTTP calls). They don't make CPU-bound work faster.
- They remove the thread-pool limit, which moves the bottleneck: 10,000 concurrent requests now try to take 10,000 database connections from a pool of 20. Limit concurrency explicitly (semaphores, bounded connection pools, rate limiters).
ThreadLocals multiply (one per virtual thread); prefer scoped values (finalised in JDK 25) for request context.- Compared with reactive (WebFlux/Reactor): similar throughput for I/O-bound services with much simpler code, debugging and stack traces; reactive still offers backpressure-aware streaming operators.
The L4 toolkit
| Symptom | First tools | What you're looking for |
|---|---|---|
| High CPU | async-profiler / JFR CPU flame graph; top -H + thread dump |
Hot methods; spin loops; GC threads (then GC logs); hash collisions (194A) |
| Latency spikes | GC log (-Xlog:gc*), JFR (safepoints, GC, locks), traces |
Pauses, allocation stalls, lock contention, slow downstream calls |
| Memory growth / OOM | jcmd <pid> GC.class_histogram, heap dump (-XX:+HeapDumpOnOutOfMemoryError), Eclipse MAT dominator tree |
Leaking collections, caches without bounds, ThreadLocals, classloader leaks |
| Container OOMKilled (no Java OOM) | Native Memory Tracking (-XX:NativeMemoryTracking=summary, jcmd VM.native_memory) |
Off-heap: metaspace, thread stacks, direct buffers, code cache, glibc arenas |
| Hung / slow throughput | Thread dumps (jcmd <pid> Thread.print, several seconds apart) |
Deadlocks (reported automatically), threads blocked on the same lock or pool |
| Slow startup | JFR startup recording, -Xlog:class+load, -verbose:gc |
Classpath scanning, eager initialisation, JIT warm-up |
JFR (Java Flight Recorder) is built in and cheap enough for production (typically under 1–2% overhead with the default profile): jcmd <pid> JFR.start duration=60s filename=rec.jfr, then open in JDK Mission Control. Make it part of the runbook.
Java in production (L6)
- Containers: the JVM reads cgroup limits (since JDK 10 / 8u191). Size the heap as a fraction (
-XX:MaxRAMPercentage=60–75) and leave room for non-heap memory (metaspace, threads, code cache, direct buffers, GC structures); OOMKilled-without-OutOfMemoryError means non-heap grew. With 1 CPU, the JVM picks Serial GC and few compiler threads: give JVM services at least 2 CPUs or set GC explicitly. - Startup and warm-up: Class Data Sharing (AppCDS), the AOT cache from Project Leyden (JDK 24+, JEP 483 and successors), CRaC (checkpoint/restore, vendor builds), or GraalVM native image (fast startup and small memory, at the cost of build time, reflection configuration and peak throughput without a JIT). Warm-up traffic before readiness (Volume 16, ch. 192).
- Upgrades: stay on an LTS (21, 25) and move within a year of the next; test with the new JDK in CI early (
--releaseflags,jdeprscan,jdeps --jdk-internalsfor internal API use); roll out by canary because GC and JIT changes alter performance. - Security: never deserialise untrusted data with Java serialisation (use
ObjectInputFilterif you must); patch dependencies promptly (Log4Shell in 2021 was a JNDI lookup in a logging library); keep the JDK patched (quarterly CPUs). - Cost: memory is usually the binding constraint for JVM services in Kubernetes; a 20% heap reduction can mean 20% fewer nodes.
Spring: the ladder
| Level | Observable behaviour |
|---|---|
| L1 | Knows Spring is a dependency-injection container with modules for web, data, security; Spring Boot provides auto-configuration |
| L2 | Builds REST services with Spring Boot: controllers, validation, Spring Data repositories, configuration properties, tests with @SpringBootTest and slices |
| L3 | Explains the container (bean definitions, lifecycle, post-processors), proxies and AOP, auto-configuration conditions, transaction management, the filter chain in Spring Security, request handling in DispatcherServlet |
| L4 | Diagnoses: transactions not applying, LazyInitializationException and N+1 queries, connection-pool exhaustion, circular dependencies, slow startup, wrong auto-configuration (--debug conditions report) |
| L5 | Chooses: MVC with virtual threads vs WebFlux; JPA vs JDBC Client vs jOOQ; transaction boundaries and isolation; modular structure (Spring Modulith); security architecture (resource server, sessions vs tokens) |
| L6 | Operates Spring services: Actuator, Micrometer metrics and tracing, graceful shutdown, upgrades across major versions (Boot 2 → 3 → 4), startup/memory tuning, native images where worth it |
How Spring's proxies work, and the self-invocation trap
Spring implements @Transactional, @Async, @Cacheable, @PreAuthorize and other cross-cutting behaviour with proxies: the bean other beans receive is a wrapper (a JDK dynamic proxy for interfaces, or a CGLIB subclass) that runs the behaviour around a call to the real object. The proxy only sees calls that go through it. A method calling another method on this bypasses the proxy, so the annotation on the inner method does nothing. The same mechanism, reproduced with a JDK proxy in 30 lines:
static class SkipServiceImpl implements SkipService {
public void skipWeek(long sub) { for (int d = 1; d <= 5; d++) skipDay(sub, d); } // self-invocation: this.skipDay
@Transactional public void skipDay(long sub, int day) { System.out.println(" skipDay(" + day + ") tx=" + TX.get()); }
}
// transactionalProxy(...) begins/commits around methods annotated @Transactional, like Spring's TransactionInterceptor
call through proxy: svc.skipDay(7, 1)
proxy: BEGIN
skipDay(1) tx=BEGIN#skipDay
proxy: COMMIT
call svc.skipWeek(7): inner calls are this.skipDay(), not the proxy:
skipDay(1) tx=none
skipDay(2) tx=none
skipDay(3) tx=none
skipDay(4) tx=none
skipDay(5) tx=none
The five inner calls run with no transaction: in a real service, a failure on day 4 leaves days 1–3 committed. Fixes: put @Transactional on the outer public method (usually what you want: one transaction for the week), move the inner method to another bean, or use TransactionTemplate programmatically. Related traps from the same mechanism: annotations on private or final methods are ignored (proxies can't intercept them); @Transactional on a method called during construction does nothing; checked exceptions don't trigger rollback by default (rollbackFor).
Transactions and data access
Propagation (REQUIRED joins or starts; REQUIRES_NEW suspends and starts a separate transaction, holding a second connection; NESTED uses savepoints) and isolation (default: the database's, Read Committed for PostgreSQL; Volume 3) are design decisions, not annotations to copy. L5 rules of thumb:
- Keep transactions short and free of remote calls (an HTTP call inside a transaction holds a connection and locks for its duration).
REQUIRES_NEWinside a loop with a pool of 10 connections deadlocks the pool at 10 concurrent requests (each holds one and waits for another).- JPA/Hibernate: great for aggregate-oriented writes; dangerous for reporting. Know the persistence context (first-level cache, dirty checking at flush), fetch plans (lazy by default for collections; N+1 when iterating),
spring.jpa.open-in-view(on by default: keeps a connection for the whole request including view rendering; turn it off), batch inserts (hibernate.jdbc.batch_sizeplus sequence-based ids), and that bulk JPQL updates bypass the persistence context. - JDBC Client /
JdbcTemplateor jOOQ for queries where SQL is the point: reports, bulk operations, PostgreSQL-specific features (chapter 194C).
MVC, WebFlux or virtual threads
| Spring MVC (platform threads) | Spring MVC + virtual threads | Spring WebFlux | |
|---|---|---|---|
| Programming model | Blocking, thread per request | Same code | Reactive types (Mono, Flux), non-blocking end to end |
| Concurrency limit | Thread pool (Tomcat default 200) | Effectively unbounded; limit downstream explicitly | Event loop; limited by downstream and backpressure |
| Debuggability | Plain stack traces | Plain stack traces | Harder; needs Reactor debugging tools |
| Libraries | All blocking libraries (JDBC, JPA) | Same | Needs reactive drivers (R2DBC) for full benefit |
| Best for | Most services | I/O-heavy services that outgrow pools | Streaming, backpressure-heavy pipelines, gateways |
Enabling virtual threads in Spring Boot 3.2+ is a property (spring.threads.virtual.enabled=true); the L5 work is everything around it: connection pool sizes, rate limits, pinning checks on JDK 21, load tests.
Spring in production (L6)
- Actuator health groups for probes (Volume 16), metrics via Micrometer (Prometheus, OTLP), tracing via Micrometer Tracing with OpenTelemetry,
/actuator/infowith build and git info, and locked-down exposure (management.endpoints.web.exposure.includeminimal, separate port). - Startup and memory: lazy initialisation for some apps, trimming auto-configurations, CDS (Spring Boot has built-in support for extracting a CDS-friendly layout), Spring AOT plus GraalVM native images when startup and memory matter more than peak throughput.
- Upgrades: Spring Boot releases a minor version every six months with about a year of open-source support each. Boot 3 moved to Jakarta EE namespaces (
javax.*→jakarta.*) and Java 17; Boot 4 / Framework 7 (November 2025) keeps a Java 17 baseline, moves to Jakarta EE 11, Jackson 3 and JSpecify null-safety annotations, and splits auto-configuration into smaller modules. Use the OpenRewrite migration recipes and the properties migrator, upgrade one minor at a time, and canary. - Security: keep Spring Security's defaults (CSRF for browser sessions, secure headers), configure as an OAuth2 resource server for APIs, and audit Actuator exposure (an exposed
/actuator/envor/heapdumpleaks secrets).
Lab: virtual threads, pinning and garbage collectors on the JVM
Setup. OpenJDK 21.0.12 on the lab machine (2 CPUs, so 2 virtual-thread carriers), single-file Java programs. Scope: small, short programs; numbers on a 2-CPU machine show the mechanisms clearly, and production behaviour depends on heap size, core count and workload.
Experiment 1: blocking tasks on three executors
10,000 tasks, each Thread.sleep(100) (standing in for a blocking HTTP or JDBC call):
| Executor | Time | Why |
|---|---|---|
| fixed pool, 200 platform threads | 5.15 s | 50 waves × 100 ms |
| fixed pool, 2,000 platform threads | 0.76 s | 5 waves, plus the cost of 2,000 OS threads |
newVirtualThreadPerTaskExecutor() |
0.27 s | all 10,000 park at once; carriers stay free |
Experiment 2: pinning
2,000 virtual threads, each blocking for 100 ms while holding a lock:
| Lock | Time |
|---|---|
synchronized (lock) { sleep } |
100.16 s |
ReentrantLock |
0.11 s |
On Java 21, a virtual thread that blocks while holding a monitor is pinned to its carrier; with 2 carriers, the 2,000 sleeps ran two at a time (2,000 × 0.1 s ÷ 2 = 100 s), a 900× slowdown from one keyword. Real code hits this through libraries that use synchronized around I/O (older JDBC drivers and HTTP clients). Diagnose with -Djdk.tracePinnedThreads=full or JFR's jdk.VirtualThreadPinned event; fix by upgrading libraries, using java.util.concurrent locks, or moving to JDK 24+ (JEP 491 removed pinning for synchronized). Note also what virtual threads don't fix: if all 10,000 tasks needed a database connection from a pool of 20, the pool, not the threads, would set the pace.
Experiment 3: collector choice and pause-shaped latency
A program allocating 3 million 1 KB arrays while keeping up to 300,000 alive (−Xmx512m); "step time" is the time for each 1,000 allocations, so a GC pause shows up as a slow step:
| Collector | Total | Step p50 | Step p99.9 | Worst step | GC log events |
|---|---|---|---|---|---|
| Serial | 0.66 s | 0.08 ms | 23.53 ms | 39.94 ms | 59 |
| Parallel | 0.47 s | 0.08 ms | 9.97 ms | 11.39 ms | 29 |
| G1 (default) | 0.70 s | 0.12 ms | 15.54 ms | 18.58 ms | 31 |
| ZGC (generational) | 0.54 s | 0.11 ms | 3.54 ms | 7.76 ms | 61 |
The shape matches each collector's design: Parallel maximises throughput with stop-the-world pauses; ZGC does most work concurrently and keeps pauses short, at the cost of CPU spent alongside the application (on 2 cores that competes directly with the program). G1 balances the two. An L5 choice starts from the service's goal (throughput for batch jobs, tail latency for APIs), then measures with GC logs and JFR under a realistic heap and load; a 0.7 s run on a laptop only shows the shape.
Try it yourself
- Rerun Experiment 2 with
-Djdk.tracePinnedThreads=fulland read the stack trace that identifies the pinning. - Add a
Semaphore(20)to Experiment 1 to model a 20-connection pool and measure the virtual-thread time. - Run Experiment 3 with
-Xmx2gand with 10× more live objects; record JFR and compare GC pause histograms. - In a Spring Boot app, reproduce the
@Transactionalself-invocation trap with a test that checks whether a rollback happened.
Revision sheet: Java and Spring at L5/L6
Key ideas
- Java Memory Model: happens-before via locks,
volatile, thread start/join, final fields; data races give stale or torn reads. - JVM: class loading, JIT tiers (C1/C2), escape analysis, GC families (Serial, Parallel, G1, ZGC, Shenandoah), JFR and unified logging.
- Virtual threads: cheap blocking concurrency; watch pinning (pre-JDK 24
synchronized), ThreadLocal usage, and downstream limits like connection pools. - L4 toolkit: thread dumps, heap dumps (MAT), JFR/JMC, async-profiler, GC logs,
jcmd. - Spring: dependency injection, proxies (self-invocation trap), transaction propagation and isolation, lazy loading and N+1, MVC vs WebFlux vs virtual threads.
- L6: JVM upgrades, container-aware memory settings, startup time (CDS, AOT), observability, capacity and cost.
Numbers to remember
- Lab: 10,000 × 100 ms tasks: 200-thread pool 5.15 s, virtual threads 0.27 s.
- Lab: pinning: 2,000 tasks in
synchronizedtook 100 s vs 0.11 s withReentrantLock(JDK 21, 2 carriers). - Lab: worst GC-shaped step 40 ms (Serial) vs 8 ms (ZGC) on a small run.
Pitfalls
- Adopting virtual threads without checking pinning and pools.
@Transactionalon private or self-invoked methods.- Default GC and heap settings in containers without measurement.
- N+1 queries hidden by ORM lazy loading.
- Diagnosing latency without GC logs and JFR.
Glossary
- Carrier thread: a platform thread that runs virtual threads.
- Pinning: a virtual thread unable to unmount from its carrier.
- happens-before: the JMM's visibility and ordering guarantee.
- JFR: Java Flight Recorder.
- Propagation: how a transactional method joins or starts transactions.