Java Materials
← Core Java · Chapter 19

Java 21 virtual threads and preview concurrency

A virtual thread is a Java thread scheduled by the JVM onto a platform carrier. The OS schedules the carrier onto a CPU core. A supported blocking operation can unmount the virtual thread, so its carrier runs other work. A resumed virtual thread may use a different carrier.

Mount, unmount and carrier scheduling

Definition:

A virtual thread is scheduled by the JVM onto a platform carrier.

Explanation:

A virtual thread retains Java call-stack state separately from the platform thread that runs it.

Illustration image:

Supported blocking I/O unmounts A. The carrier can execute B, and A becomes runnable when its I/O result is available. A carrier runs another task while A waitsCarrier CVirtual AA runsB runsA resumesI/O waitA can resume on C or another carrier
Supported blocking I/O unmounts A. The carrier can execute B, and A becomes runnable when its I/O result is available.

Example:

Worked Java example · see surrounding context in notes
Thread task = Thread.startVirtualThread(() ->
    System.out.println(Thread.currentThread().isVirtual()));
task.join();

Expected behavior. Prints true. The Java thread remains the logical request identity even when it runs on a different carrier later.

Internal working:

Supported blocking operations let the JVM suspend that execution so the carrier can run another task. A virtual thread does not create extra CPU cores. Measure throughput and latency under real downstream limits rather than equating higher concurrency with higher work capacity.

Interview questions:

What does a virtual thread release during supported I/O?

It can unmount from the carrier, allowing that platform thread to run another virtual task while I/O completes.

Java 21 pinning and resource limits

Definition:

Pinning prevents a virtual thread from unmounting from a carrier in a particular situation.

Explanation:

In Java 21, blocking inside an intrinsic monitor or certain native paths can pin the carrier.

Illustration image:

Java 21 pinning and resource limits. Enter monitor · Blocking operation · Carrier stays occupied · Other tasks waitJava 21 pinning and resource limitsSource or actorEnter monitorFirst boundaryBlocking operationInspected stateCarrier stays occupiedObservable effectOther tasks wait
Enter monitor · Blocking operation · Carrier stays occupied · Other tasks wait

Example:

Shell / diagnostic commands
java -Djdk.tracePinnedThreads=short -jar application.jar

Expected behavior. Use the Java 21 diagnostic during a controlled run. Prefer JFR for correlated evidence and avoid dumping noisy stacks indefinitely.

Internal working:

Keep blocking I/O out of shared critical sections where correctness allows. Compare pinned events with latency and runnable work before refactoring. Later JDKs can change pinning behavior, so use the exact runtime version in diagnostics.

Interview questions:

Why can Java 21 slow down if blocking work runs under synchronized?

In Java 21, that path can pin the carrier, reducing carriers available to execute other tasks.

Task-per-request and structured alternatives

Definition:

Thread-per-task separates request concurrency from the capacity of dependencies.

Explanation:

Create virtual threads per task instead of pooling them to impose backend limits.

Illustration image:

Task-per-request and structured alternatives. Many virtual tasks · Four database permits · Wait with deadline · Release permitTask-per-request and structured alternativesSource or actorMany virtual tasksFirst boundaryFour database permitsInspected stateWait with deadlineObservable effectRelease permit
Many virtual tasks · Four database permits · Wait with deadline · Release permit

Example:

Worked Java example · see surrounding context in notes
try (var executor = java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor()) {
    var result = executor.submit(() -> {
        permits.acquire();
        try { return database.readOrder(); }
        finally { permits.release(); }
    });
    System.out.println(result.get());
}

Expected behavior. The executor permits many request tasks while the semaphore limits database calls.

Internal working:

Use a connection pool or semaphore for a scarce resource. Avoid costly ThreadLocal object caches on huge virtual-thread populations. CompletableFuture remains suitable for dependency graphs and reactive streams for demand-driven streams. Java 21 structured concurrency and scoped values are preview capabilities.

Interview questions:

How should you limit calls to a database from virtual threads?

Use the connection pool or a semaphore and an admission deadline, rather than pooling the virtual threads themselves.

Reference subtopics

Creation and overload

Thread.ofVirtual builds virtual threads; startVirtualThread starts one directly. Executors.newVirtualThreadPerTaskExecutor creates one per submitted task. Keep simple blocking code for high-concurrency I/O, but CPU-bound throughput remains limited by cores. Avoid pooling virtual threads to throttle them; bound database connections, remote quotas or concurrency instead.

Pinning and thread-local usage

In Java 21, blocking inside a synchronized region or certain native calls can pin a virtual thread to its carrier. Confirm impact with JFR or the JDK diagnostic before changing synchronization. Do not put heavyweight objects in per-thread state merely to reuse them across virtual requests; each task generally receives its own thread.

Comparing models and preview features

Use virtual threads when blocking APIs and straight-line code fit the system. CompletableFuture expresses dependency graphs; reactive pipelines express asynchronous streams and backpressure. Java 21 structured concurrency and scoped values are preview features: compile and run with the 21 preview flags and use the release-specific APIs.

Run the complete Java labs ↗ · Java reference ↗