Skip to main content
Advanced Architecture & Engineering 12 min read Java 21 LTS (Project Loom • JEP 444)

Java 21 Virtual Threads and Modern Multithreading Guide

Scale synchronous Spring Boot and JDBC code cleanly to tens of thousands of concurrent I/O requests using Java 21 Virtual Threads.

Written by Ravi Shankar Mishra (Founder & Lead Systems Architect, MockAttempt Academy) Reviewed by MockAttempt Engineering Editorial Desk
Last updated: Verification Policy

Learning Objectives

  • Explain how JVM virtual threads mount and unmount cleanly onto OS carrier threads during blocking I/O.
  • Identify when to choose virtual threads vs bounded platform pools vs async reactive stacks.
  • Eliminate carrier thread pinning by preferring `ReentrantLock` over long `synchronized` I/O blocks on Java 21.

Prerequisites

  • Java Multithreading fundamentals (`Runnable`, `ExecutorService`, `CompletableFuture`)

Why Platform Threads Hit a Scaling Wall

Traditional java.lang.Thread instances map 1:1 to heavyweight operating-system kernel threads (~1 MB default stack reserve plus expensive OS context switches). When a Tomcat service blocks waiting for PostgreSQL queries or downstream HTTP microservices, a 200-thread pool caps throughput artificially even while CPU cores sit largely idle.

Finalized in Java 21 LTS (JEP 444), Virtual Threads are lightweight JVM-managed continuations scheduled atop a small ForkJoinPool of OS carrier threads. Whenever a virtual thread hits a JDK blocking call (Socket, Thread.sleep, JDBC drivers on Java 21), the JVM unmounts its stack chunk to the heap so the carrier thread immediately executes another virtual thread.

Do Not Pool Virtual Threads

Unlike scarce platform threads, you never place virtual threads inside a fixed-size pool. Spawn one per unit of concurrent work with Executors.newVirtualThreadPerTaskExecutor() and use a Semaphore when you need concurrency backpressure against a database connection limit.

Put this directly into practice with our Spring Boot Dependency Injection Guide, practice Java Concurrency MCQs, or train live in the Java Backend Career Program.

Practical Programming Examples

Running 1,000 Concurrent I/O Tasks cleanly with Virtual Threads (JDK 21)

Execute 1,000 concurrent blocking calls using Executors.newVirtualThreadPerTaskExecutor and verify fast completion without OOM.

JDK 21 LTS (javac / java)
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class VirtualThreadLab {
    public static void main(String[] args) {
        var completed = new AtomicInteger();

        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < 1_000; i++) {
                executor.submit(() -> {
                    Thread.sleep(Duration.ofMillis(40));
                    completed.incrementAndGet();
                    return null;
                });
            }
        } // Auto-closes and waits cleanly until all 1,000 tasks complete

        System.out.println("Completed tasks = " + completed.get());
    }
}
Expected Output
Completed tasks = 1000
Step-by-Step Execution
  1. `try (var executor = Executors.newVirtualThreadPerTaskExecutor())` guarantees structured shutdown and completion waiting.
  2. While each task executes `Thread.sleep(40ms)`, the JVM unmounts the virtual thread off its carrier OS thread.
  3. All 1,000 tasks finish concurrently in roughly ~50–100 ms rather than 40+ seconds.

Common Mistakes to Avoid

  • Holding a `synchronized` lock across slow HTTP or JDBC I/O calls inside Java 21, pinning the virtual thread to its carrier OS thread.
  • Expecting Virtual Threads to speed up CPU-bound prime/video crunching loops (CPU parallelism still depends strictly on core count).

Production Best Practices

  • Replace `synchronized` guards around network/DB calls with `ReentrantLock` in Java 21 libraries.
  • Control downstream database saturation using a bounded `Semaphore` + HikariCP pool instead of artificially sizing thread pools.

Technical Interview Relevance

High-signal SDE-1/SDE-2 Java 21 interview topic distinguishing green/virtual threads from `CompletableFuture` reactive pipelines.

Practice & Self-Check Questions

Why should you guard a database pool with a `Semaphore` instead of a fixed Virtual Thread pool?

Virtual threads are cheap task wrappers (one per request); limiting concurrency per external resource via a Semaphore preserves the per-task thread model without starving unrelated work.

Optional Next Step

Have Questions About Learning Core Java Structured Cohorts?

Request the JBCP syllabus & weekend batch schedule from an Academic Counselor.

View JBCP Details →
Learn. Practise. Prove. Get Career-Ready.

Ready to Build Your IT Career?

Explore industry-led programmes and develop practical skills through training, assessments and interview preparation.