Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Migrate a Blocking Spring Boot Service
to Java Virtual Threads Without Pinning.

Diagnose carrier-thread pinning, HikariCP connection exhaustion, and ThreadLocal memory bloat when enabling Java 21+ Virtual Threads on a high-throughput Spring Boot service.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

To keep the architecture evolvable without sacrificing reliability, enable spring.threads.virtual.enabled=true, swap synchronized I/O guards for ReentrantLock, bound downstream fan-out with Semaphores, and replace ThreadLocal caches with ScopedValue.

TL;DR30-second simplified summary
▾

Core Mechanics: After enabling Java 21 Virtual Threads (spring.threads.virtual.enabled=true) in a Spring Boot API fanning out to 3 REST services and Postgres at 10,000+ req/s, p99 latency spikes under load and JFR emits jdk.VirtualThreadPinned events.

Visual & Structural Flow: Depicts synchronized Pinning vs. ReentrantLock Unmounting (VirtualThread #1 -> OS Carrier (Core 1) -> VirtualThread #2 -> Postgres / REST); Unmounted I/O Fan-Out with Structured Concurrency & Bulkheads (Tomcat (VT Enabled) -> ReentrantLock -> Semaphore / Hikari -> StructuredTaskScope).

Trade-Offs & Production: Simply flipping spring.threads.virtual.enabled=true without auditing JDBC drivers, synchronized blocks, ThreadLocals, and HikariCP pool sizes leaves. Migrate Spring Boot imperative services safely to 10,000+ RPS on Java 21: Eliminate Pinning: Enable -Djdk.tracePinnedThreads=full / JFR jdk.VirtualThreadPinned in staging.

Failure Modes & Application: Virtual threads bridge imperative simplicity with reactive scalability: BFF & API Aggregators: Fanning out to multiple REST/gRPC/DB backends concurrently with StructuredTaskScope.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Java Virtual Threads & Structured Concurrency
Java 21+ Virtual Threads (Project Loom) are lightweight, JVM-scheduled threads multiplexed onto a small ForkJoinPool of OS carrier threads. Blocking I/O unmounts the virtual thread instead of blocking an OS thread—unless pinned by synchronized blocks (fixed in...
Modern Java (8 to 25): Records, Sealed Classes, Pattern Matching & Lambdas
Modern Java combines immutable record data carriers, sealed algebraic data hierarchies, and exhaustive switch pattern matching with Streams and Lambdas—turning verbose boilerplate into compiler-verified domain models.
Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why Virtual Threads & Pinning Prevention Matter.

Why this matters: The mechanism: understand how Why Virtual Threads & Pinning Prevention Matter works from first principles.

Think of Why Virtual Threads & Pinning Prevention Matter as the intuition layer for Migrate a Blocking Spring Boot Service to Java Virtual Threads Without Pinning: The mechanism: understand how Why Virtual Threads & Pinning Prevention Matter works from first principles.

After enabling Java 21 Virtual Threads (spring.threads.virtual.enabled=true) in a Spring Boot API fanning out to 3 REST services and Postgres at 10,000+ req/s, p99 latency spikes under load and JFR emits jdk.VirtualThreadPinned events. While keeping imperative JDBC/RestClient code, we must eliminate carrier-thread pinning and bound downstream fan-out.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

Real-World Impact of Carrier-Thread Pinning.

Why this matters: The problem: see what breaks without Real-World Impact of Carrier-Thread Pinning under real concurrency or scale.

In Java 21, virtual threads are multiplexed onto a small pool of OS carrier threads (sized to CPU cores):

  1. Carrier Pinning (synchronized): Blocking on JDBC/HTTP inside a synchronized block pins the virtual thread to its OS carrier thread—starving all other virtual threads.
  2. Downstream Pool Exhaustion: Spawning 10,000+ concurrent virtual threads without a bulkhead slams Postgres max_connections.
  3. ThreadLocal Memory Bloat: Legacy ThreadLocal buffers (SimpleDateFormat, byte arrays) duplicated across 100k virtual threads exhaust heap.
Virtual Thread Carrier Scheduling

synchronized Pinning vs. ReentrantLock Unmounting

VirtualThread #1OS Carrier (Core 1)VirtualThread #2Postgres / REST1. Naive: synchronized {jdbc.query() }2. Pinned! VT#2 starved waitingfor carrier3. Fixed: ReentrantLock.lock() +jdbc.query()4. VT#1 unmounts on I/O -> VT#2runs on carrier!

Replacing synchronized around blocking I/O with ReentrantLock lets virtual threads unmount cleanly from OS carriers.

Engineering Decision Framework
Problem
How to implement Migrate a Blocking Spring Boot Service to Java Virtual Threads Without Pinning without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
To keep the architecture evolvable without sacrificing reliability, enable spring.threads.virtual.enabled=true, swap synchronized I/O guards for ReentrantLock, bound downstream fan-out with Semaphores, and replace ThreadLocal caches with ScopedValue.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Migrate a Blocking Spring Boot Service to Java Virtual Threads Without Pinning experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Naive Solution (and Why It Breaks).

Why this matters: The problem: see what breaks without Naive Solution under real concurrency or scale.

Think of Naive Solution (and Why It Breaks) as the intuition layer for Migrate a Blocking Spring Boot Service to Java Virtual Threads Without Pinning: The problem: see what breaks without Naive Solution under real concurrency or scale.

Simply flipping spring.threads.virtual.enabled=true without auditing JDBC drivers, synchronized blocks, ThreadLocals, and HikariCP pool sizes leaves jdk.VirtualThreadPinned stalls intact and causes HikariCP connectionTimeout storms when 10,000 virtual threads compete for 20 DB connections.

Request & State Flow

Naive Solution (and Why It Breaks)

Client TxPlanner / Lock MgrWAL / MemTableHeap / SSTable1. Acquire snapshot / index plan2. Append redo record + fsync WAL3. Flush dirty pages / compactSSTables4. Commit & release row locks
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise Solution: `ReentrantLock`, `Semaphore` Bulkheads & `ScopedValue`.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Migrate Spring Boot imperative services safely to 10,000+ RPS on Java 21:

  • Eliminate Pinning: Enable -Djdk.tracePinnedThreads=full / JFR jdk.VirtualThreadPinned in staging; replace synchronized blocks guarding I/O (and upgrade older JDBC/logging libraries) with ReentrantLock.
  • Bound Downstream Concurrency: Never pool virtual threads (newVirtualThreadPerTaskExecutor()); use Semaphore bulkheads and StructuredTaskScope.ShutdownOnFailure for the 3-way REST + Postgres fan-out.
  • Replace ThreadLocal with ScopedValue: Pass request/trace context via immutable ScopedValues instead of heavy per-thread ThreadLocal caches.
Java 21 Virtual Thread Architecture

Unmounted I/O Fan-Out with Structured Concurrency & Bulkheads

Tomcat (VT Enabled)10,000+ virtual…ReentrantLockZero carrier pinningSemaphore / HikariBounded DB & REST…StructuredTaskScope3 REST + PG parallelFail-fast cancel

1.ReentrantLock: Allows JVM to park/unmount virtual thread during I/O wait.

2.Structured Fan-Out: ShutdownOnFailure cancels remaining REST calls if one fails.

3.ScopedValue: Zero-copy immutable context inherited by child virtual threads.

4.JFR Audit: Monitor jdk.VirtualThreadPinned events in CI load tests.

ReentrantLock, Semaphore bulkheads, and StructuredTaskScope unlock 10k+ RPS imperative Java without carrier pinning.

import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;

public class OrderAggregationService {
    private final ReentrantLock cacheLock = new ReentrantLock();
    private final Semaphore dbBulkhead = new Semaphore(50);

    public OrderView fetchOrder(String orderId) throws Exception {
        try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
            var pricing = scope.fork(() -> callPricingApi(orderId));
            var inventory = scope.fork(() -> callInventoryApi(orderId));
            var ledger = scope.fork(() -> queryPostgresBounded(orderId));
            scope.join().throwIfFailed();
            return new OrderView(pricing.get(), inventory.get(), ledger.get());
        }
    }

    private LedgerRow queryPostgresBounded(String id) throws InterruptedException {
        dbBulkhead.acquire();
        try {
            return jdbcTemplate.queryForObject("SELECT * FROM orders WHERE id=?", rowMapper, id);
        } finally {
            dbBulkhead.release();
        }
    }
}
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where Virtual Threads Apply in System Design.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Virtual threads bridge imperative simplicity with reactive scalability:

  • BFF & API Aggregators: Fanning out to multiple REST/gRPC/DB backends concurrently with StructuredTaskScope.
  • High-Concurrency Spring Boot Microservices: Replaces complex WebFlux reactive chains when libraries are blocking.
  • Legacy JDBC Services: Scales connection-waiting concurrency without rewriting SQL layers.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why does `synchronized` around a blocking JDBC call degrade throughput under Java 21 Virtual Threads?

Recommended Learning Flow