Chapter 10 of 12
Course Progress0 of 12 completed (0%)

Java & Spring Boot Enterprise Mastery · Chapter 10 · ~15 min · Advanced

Concurrency, Thread Pools & Virtual Threads (Project Loom)

Step into modern Java 21 concurrency. Contrast heavy OS platform threads against millions of lightweight Virtual Threads, understand M:N carrier thread scheduling on the ForkJoinPool, prevent thread pinning in synchronized blocks, and master Structured Concurrency.

  • Compare OS platform threads (1MB stack) with lightweight Virtual Threads
  • Understand M:N carrier thread scheduling and non-blocking I/O unmounting
  • Identify and prevent thread pinning caused by synchronized blocks
  • Coordinate concurrent subtasks safely using StructuredTaskScope

Concurrency, Thread Pools & Virtual Threads (Project Loom): learn it visually

Step into modern Java 21 concurrency. Contrast heavy OS platform threads against millions of lightweight Virtual Threads, understand M:N carrier thread scheduling on the ForkJoinPool, prevent thread pinning in synchronized blocks, and master Structured Concurrency.

Concurrency, Thread Pools & Virtual Threads (Project Loom)Step into modern Java 21 concurrency. Contrast heavy OS platform threads against millions of lightweight Virtual Threads, understand M:N carrier thread scheduling on the ForkJoinPool, prevent thread pinning in synchronized blocks, and master Structured Concurrency.UNDERSTANDSubmit a taskFOLLOW THE FLOWABCDSchedule workerthreadsAPPLY ITRun virtual threadsConcurrency, Thread Pools & Virtual Threads (Project Loom)Step into modern Java 21 concurrency. Contrast heavy OS platform threads against millions of lightweight Virtual Threads, understand M:N carrier thread scheduling on the ForkJoinPool, prevent thread pinning in synchronized blocks, and master Structured Concurrency.UNDERSTANDSubmit a taskFOLLOW THE FLOWABCDSchedule workerthreadsAPPLY ITRun virtual threads

1The Architecture of Virtual Threads (Project Loom)

For three decades, Java followed a 1:1 thread model: every java.lang.Thread created in your application was a direct wrapper around an Operating System kernel thread. Because each OS thread requires ~1MB of off-heap stack memory and expensive context switching, enterprise servers were constrained to a few hundred threads.

Virtual Threads (finalized in Java 21) introduce an M:N scheduling model. The JVM manages millions of virtual threads running on top of a small pool of OS carrier threads (typically equal to the number of available CPU cores):

// Launching a Virtual Thread in Java 21
Thread vThread = Thread.ofVirtual()
    .name("order-worker-", 0)
    .start(() -> {
        System.out.println("Running on virtual thread: " + Thread.currentThread());
    });

// Or using an ExecutorService with millions of virtual tasks:
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    IntStream.range(0, 10_000).forEach(i -> {
        executor.submit(() -> {
            Thread.sleep(Duration.ofSeconds(1)); // Unmounts automatically from carrier!
            return i * 2;
        });
    });
} // Executor automatically waits for all tasks to complete on try-with-resources exit!
Concept Check

What happens when a Java 21 Virtual Thread invokes a blocking operation like Thread.sleep() or a database query?

2Dual Mental Model: 1:1 OS Threads vs M:N Virtual Threads

Compare traditional thread-per-request architectures against lightweight Java 21 Virtual Threads:

Wrong idea: Heavy 1:1 OS platform threads allocating 1MB stack memory each

10,000 requests = 10,000 OS Threads × 1MB Stack = 10 GB RAM → OutOfMemoryError!Massive memory overhead · costly OS context switching · pool starvation

Mapping each Java thread directly to an operating system kernel thread with fixed 1MB off-heap stack memory, causing OutOfMemoryError past ~2,000 threads.

Real system: Lightweight M:N Virtual Threads allocated on the Java heap

1,000,000 Virtual Threads × ~1 KB Heap = ~1 GB RAM on standard serverMillions of concurrent threads · zero OS context switches · near-zero cost

Decoupling Java threads from OS threads: millions of virtual threads exist as simple heap objects requiring only a few hundred bytes, managed entirely by the JVM.

3The Thread Pinning Hazard: synchronized vs ReentrantLock

While Virtual Threads effortlessly scale standard imperative Java code, there is one major hazard: Thread Pinning. A virtual thread becomes pinned to its carrier thread when:

  • It executes a blocking operation inside a legacy synchronized block or synchronized method
  • It executes a blocking operation inside a native JNI method or foreign function
Why Thread Pinning Starves Server Carrier Cores:

// Dangerous: Carrier thread cannot unmount!
synchronized (lock) {
    httpClient.send(request); // Blocks for 200ms → Pins carrier CPU thread!
}
// If all 8 CPU cores are pinned by 8 sleeping threads, all 100,000 other virtual threads freeze!

The solution is to replace synchronized with java.util.concurrent.locks.ReentrantLock:

@Component
public class VirtualThreadFriendlyRateLimiter {

    // ReentrantLock does NOT pin carrier threads!
    private final ReentrantLock lock = new ReentrantLock();

    public void accessSharedResource() {
        lock.lock();
        try {
            // Virtual thread can safely unmount here if blocking occurs!
            remoteAuditService.recordAudit();
        } finally {
            lock.unlock();
        }
    }
}
Concept Check

Why does replacing 'synchronized' with 'ReentrantLock' solve thread pinning in Virtual Threads?

4Interactive Visualizer: Carrier Thread Scheduler

Simulate how the ForkJoinPool carrier threads handle 5,000 concurrent requests across Virtual Threads, traditional thread pools, and thread pinning:

M:N Carrier Thread & Virtual Thread Scheduler

Observe how the ForkJoinPool carrier threads unmount virtual threads during blocking I/O versus traditional OS thread pools

Java 21 Project Loom

Select Concurrency Architecture Mode:

Concurrent Requests

5,000

OS Kernel Threads

8 Cores (Fixed Carrier)

RAM Stack Overhead

~5.2 MB (Heap Objects)

Throughput Status

50,000 req/sec (High)

Carrier ForkJoinPool (4 Hardware CPU Cores)
NON-BLOCKING UNMOUNTING
CarrierCore-1
Status: ACTIVE (100% util)
VT-#104 running; VT-#101 unmounted to heap
CarrierCore-2
Status: ACTIVE (100% util)
VT-#204 running; VT-#201 unmounted to heap
CarrierCore-3
Status: ACTIVE (100% util)
VT-#304 running; VT-#301 unmounted to heap
CarrierCore-4
Status: ACTIVE (100% util)
VT-#404 running; VT-#401 unmounted to heap

When a Virtual Thread calls Thread.sleep(), JDBC queries, or HTTP requests, it unmounts from its carrier thread and parks on the JVM heap. The carrier thread immediately executes the next ready virtual thread, yielding near-infinite concurrency!

5Structured Concurrency with StructuredTaskScope

Traditional multi-threaded code often produces thread leaks: if one subtask fails or times out, sibling threads continue running in the background, wasting CPU and database resources. Java 21's Structured Concurrency (StructuredTaskScope) treats concurrent subtasks as a single unit of work:

public record AggregatedUserProfile(User user, List<Order> orders, CreditScore score) {}

public class UserAggregationEngine {

    public AggregatedUserProfile fetchProfileConcurrently(Long userId) throws Exception {
        // StructuredTaskScope.ShutdownOnFailure: If any subtask fails, cancel all others immediately!
        try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
            
            Subtask<User> userTask = scope.fork(() -> userService.findUser(userId));
            Subtask<List<Order>> ordersTask = scope.fork(() -> orderService.findOrders(userId));
            Subtask<CreditScore> scoreTask = scope.fork(() -> creditService.fetchScore(userId));

            scope.join();           // Join all subtasks
            scope.throwIfFailed();  // Propagate first failure and cancel siblings!

            // Both tasks succeeded: safely extract results
            return new AggregatedUserProfile(userTask.get(), ordersTask.get(), scoreTask.get());
        } // Exiting scope automatically shuts down and cleans up any uncompleted threads!
    }
}

6Code Bug Hunt: Thread Pinning Under Synchronized Monitor

The CurrencyExchangeService below suffers from carrier thread pinning caused by a synchronized block wrapping a blocking I/O operation. Refactor it to use ReentrantLock so virtual threads can unmount freely:

Eliminate Thread Pinning with ReentrantLock
Java

🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.

Need a hint?
  • Replace private final Object monitorLock = new Object(); with a ReentrantLock instance (e.g. private final ReentrantLock lock = new ReentrantLock();).
  • Remove the synchronized (monitorLock) block. Synchronized object monitors pin the Virtual Thread to its carrier OS thread during blocking I/O calls.
  • Use the idiomatic lock pattern: lock.lock(); try { ... } finally { lock.unlock(); } so the carrier thread can unmount safely during I/O waits.

7Chapter Knowledge Challenge

Verify your understanding of modern Java concurrency and virtual threads:

Concept Check 1 of 2
1

Should you pool Virtual Threads using a ThreadPoolExecutor like you did with platform threads?

Concept Check 2 of 2
2

How do you enable Virtual Threads for Spring Boot 3 web servers in application.yml?

8Recap

  • Virtual Threads decouple Java threads from OS threads, supporting millions of concurrent tasks on a small pool of carrier threads.
  • When a virtual thread encounters blocking I/O, it automatically unmounts to the heap, freeing the carrier thread to execute other work.
  • Avoid Thread Pinning by replacing synchronized blocks around blocking I/O with ReentrantLock.
  • StructuredTaskScope brings clean parent-child task hierarchies, short-circuiting sibling tasks immediately when one fails.

Ready for Chapter 11? Mark this chapter as complete to proceed:

Enjoying this free lesson? Your support helps us build more free animated chapters.

Support Us