CS › JVM

Java 21 virtual threads scheduling and carrier pinning

How Java 21 virtual threads schedule on ForkJoinPool carriers, why synchronized blocks cause pinning, and how to adopt them safely in Spring Boot 3.2+.

Java 21 virtual threads scheduling and carrier pinning

Java 21 Virtual Threads (JEP 444) let you handle tens of thousands of concurrent I/O requests while keeping familiar blocking code. This post breaks down how Carrier Threads and Continuations schedule virtual threads, how to diagnose synchronized pinning, and what to watch for when enabling them in Spring Boot 3.2+.

Tested on Java 21 LTS (JEP 444 Virtual Threads) and Spring Boot 3.2+ (Kotlin 1.9 / Java 21).

Why platform threads bottleneck on blocking I/O

In a traditional Spring MVC (Tomcat) app, the thread-per-request model assigns one Platform Thread to each incoming request, mapped 1:1 to an OS kernel thread. That model keeps code straightforward and stack traces readable, but each platform thread reserves roughly 1 MB of stack memory and incurs OS context-switching overhead. Because of that cost, most teams cap Tomcat’s worker pool at around 200 threads.

The problem is that typical backend services spend most of their time waiting on database queries or downstream HTTP APIs, not burning CPU. Once all 200 OS threads are parked waiting on sockets, your CPU sits mostly idle while new requests queue up and time out. Reactive stacks like Spring WebFlux avoid blocking threads, but they come with a steep learning curve, harder stack traces, and limited JDBC driver support. (For a closer look at how blocking vs. non-blocking I/O works in the kernel, see blocking and non-blocking I/O with epoll in Tomcat vs. Netty.)

Virtual Threads take a different path: they are M:N user-mode lightweight threads managed by the JVM. You keep synchronous, readable code while scaling I/O concurrency orders of magnitude higher.

How Carrier Threads and Continuations schedule virtual threads

Virtual threads aren’t scheduled by the OS kernel. Instead, the JVM schedules them on a FIFO-mode ForkJoinPool whose default parallelism matches the number of available CPU cores. The underlying platform thread that actually executes instructions on a CPU core is called a Carrier Thread. Each virtual thread’s call stack (StackChunk) lives on the JVM heap inside a Continuation object, growing and shrinking dynamically.

When a virtual thread mounts onto a carrier thread and hits a JDK-aware blocking operation—like socket I/O, LockSupport.park(), or Thread.sleep()—the runtime calls VirtualThread.park(). The JVM freezes the Continuation, copies its stack frames to the heap, unmounts the virtual thread from the carrier, and registers the socket with an internal Poller backed by epoll (Linux) or kqueue (macOS).

flowchart TD
    A["Virtual thread runs (mounted on Carrier)"] --> B["JDK blocking I/O call (VirtualThread.park)"]
    B --> C["Save StackChunk to heap and unmount"]
    C --> D["Carrier immediately runs another virtual thread"]
    C -->|"I/O ready (Poller signal)"| E["Re-enqueue and mount on an idle Carrier"]

The freed carrier thread immediately picks up another runnable virtual thread from the ForkJoinPool queue. When the network response arrives, the Poller unparks the waiting virtual thread and submits it back to the scheduler to mount on the next available carrier.

Platform threads vs. virtual threads vs. WebFlux

DimensionPlatform Threads (MVC)Virtual Threads (Java 21+)Reactive (WebFlux)
Thread mapping1:1 OS kernel threadsM:N (ForkJoinPool carriers)Few event-loop threads (non-blocking)
Stack and creation costHigh (~1 MB fixed stack)Very low (a few KB heap StackChunk)No per-request thread allocation
Blocking I/O behaviorHolds OS thread until I/O finishesAuto-unmounts for high concurrencyBlocking stalls the event loop
Code and debuggingSimple (synchronous, full traces)Simple (keeps synchronous style)Complex (async chains, harder traces)
Best-fit workloadsLow-concurrency internal/admin APIsI/O-heavy MVC services (DB, REST)Ultra-high-density streaming/gateways

Think of Little’s Law (Throughput = Concurrency / Latency). Virtual threads don’t make a single database query or HTTP call finish faster. They raise the concurrency ceiling during I/O waits so your server can sustain far higher throughput before queuing. (If you’re weighing virtual threads against Kotlin coroutines on the JVM, I compared both in Kotlin coroutines vs. Java 21 virtual threads.)

Diagnosing synchronized pinning and switching to ReentrantLock

The biggest trap in Java 21 is carrier pinning. If a virtual thread performs a blocking I/O call while inside a synchronized block (object monitor) or a native JNI frame, the JVM cannot detach the monitor ownership from the carrier thread. Unmounting is blocked, and the carrier stays tied up for the entire I/O wait. On a 4-core container, just four concurrent pinned requests freeze every carrier thread and tank throughput.

You can catch pinning during load tests with -Djdk.tracePinnedThreads=full or by recording the jdk.VirtualThreadPinned JFR event. In Java 21, replacing synchronized blocks that wrap I/O with ReentrantLock allows the virtual thread to unmount cleanly. Note that Java 24 (JEP 491) resolved synchronized pinning at the JVM level, so this constraint disappears once you upgrade—but on Java 21 LTS, auditing both your own code and older JDBC drivers is mandatory.

1
2
# Print full stack traces whenever a virtual thread pins its carrier
java -Djdk.tracePinnedThreads=full -jar app.jar

In Spring Boot 3.2+, enabling virtual threads for Tomcat and @Async takes a single property:

1
2
3
4
5
# src/main/resources/application.yml
spring:
  threads:
    virtual:
      enabled: true

When fanning out parallel external API calls, skip fixed thread pools and pair Executors.newVirtualThreadPerTaskExecutor() with a ReentrantLock for critical sections and a Semaphore to cap downstream concurrency:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// src/main/kotlin/com/example/demo/VirtualThreadClient.kt
package com.example.demo

import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.time.Duration
import java.util.concurrent.Executors
import java.util.concurrent.Semaphore
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock

class VirtualThreadClient {
    private val httpClient = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(3))
        .build()

    private val cacheLock = ReentrantLock()
    private val tokenCache = mutableMapOf<String, String>()
    private val concurrencyLimit = Semaphore(50)

    fun fetchAll(urls: List<String>): List<String> {
        Executors.newVirtualThreadPerTaskExecutor().use { executor ->
            val futures = urls.map { url ->
                executor.submit<String> {
                    concurrencyLimit.acquire()
                    try {
                        callExternalApi(url)
                    } finally {
                        concurrencyLimit.release()
                    }
                }
            }
            return futures.map { it.get() }
        }
    }

    private fun callExternalApi(url: String): String {
        val token = cacheLock.withLock {
            // ReentrantLock unmounts cleanly from the carrier even when token I/O blocks
            tokenCache.getOrPut("api") { fetchAccessToken() }
        }
        val request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .header("Authorization", token)
            .GET()
            .build()
        return httpClient.send(request, HttpResponse.BodyHandlers.ofString()).body()
    }

    private fun fetchAccessToken(): String {
        val req = HttpRequest.newBuilder()
            .uri(URI.create("https://auth.example.com/oauth/token"))
            .POST(HttpRequest.BodyPublishers.noBody())
            .build()
        return httpClient.send(req, HttpResponse.BodyHandlers.ofString()).body()
    }
}

Production pitfalls and when not to use virtual threads

Warning: Flipping spring.threads.virtual.enabled=true while keeping old thread-pooling and ThreadLocal caching habits can trigger heap OOMs or overload downstream databases.

First, never pool virtual threads. Creating a virtual thread costs microseconds and a few kilobytes; pooling them defeats their lifecycle model. If you used a fixed thread pool to rate-limit calls to a fragile downstream API, replace that pool with a Semaphore instead.

Second, audit ThreadLocal usage for heavy object caching. Caching a 64 KB buffer or XML parser in a ThreadLocal was harmless with 200 platform threads (~12 MB). With 50,000 concurrent virtual threads, that same cache balloons to over 3 GB and causes an OutOfMemoryError. Strip out per-thread object caches, and move toward ScopedValue (preview in Java 21) for immutable context propagation.

Third, virtual threads don’t help CPU-bound work or tiny database pools. Hashing, encryption, or image processing cannot run faster than your physical CPU cores, and virtual threads actually add slight scheduling overhead there. Likewise, if your HikariCP pool only has 10 connections, spawning 5,000 virtual threads just moves the queue from Tomcat into HikariCP’s connection wait list.

Before enabling virtual threads in production, verify these four items:

  • Run a load test with -Djdk.tracePinnedThreads=full or JFR jdk.VirtualThreadPinned and confirm zero pinning on hot paths (including JDBC drivers and logging appenders).
  • Replace synchronized blocks that execute I/O with ReentrantLock on Java 21 LTS.
  • Remove heavy ThreadLocal object caches and confirm heap growth stays bounded under peak concurrency.
  • Protect downstream APIs and databases with explicit Semaphore limits or rate limiters rather than relying on Tomcat’s thread cap.
This post is licensed under CC BY 4.0 by the author.