Java 21 virtual threads explained: before and after

For more than two decades every Java thread was glued to an operating-system thread, and a thread waiting on a database held that OS thread hostage. Virtual threads cut the glue. Here is the old model, the problem it caused, and exactly what virtual threads fix.

Two panels. Left, before: five Java threads labelled req-1 to req-200, each with an arrow to its own OS thread, and a note that the pool is full at 200 so request 201 waits. Right, Java 21: twenty yellow dots standing for 10,000 virtual threads, sharing four carrier threads, with a note that a waiting thread steps off its carrier so the carrier can run another.
Fig. 1 — Before Java 21, one Java thread meant one OS thread. With virtual threads, thousands of threads share a handful of OS threads.

Picture a restaurant with 200 waiters. Each waiter takes an order, walks it to the kitchen, and then stands at the kitchen door until the food is ready. When all 200 are standing at the door, customer 201 waits at the entrance, even though nobody is actually busy. The waiters aren’t the problem. The rule “one waiter per order, start to finish” is.

That was Java’s threading model for most of its life. Java 21, released in September 2023, made virtual threads a standard feature (JEP 444; see all Java 21 features), and they change that rule. This article tells the story in order: how threads worked before, the problem that caused, and what virtual threads do differently.

How Java threads worked before Java 21

One Java thread = one OS thread

When you write new Thread(...) or use a thread pool, you get what Java now calls a platform thread. A platform thread is a thin wrapper around an operating-system thread. The mapping is one to one:

  • You start a Java thread → the JVM asks the OS to create a real OS thread.
  • The OS scheduler decides when that thread runs on a CPU core.
  • When the Java thread ends, the OS thread is destroyed.

The Java thread is bound to its OS thread for its whole life. It can’t let go of it, even for a moment.

OS threads are expensive

OS threads are a heavyweight, shared resource:

  • Memory. Each thread gets its own stack. On 64-bit Linux the default reserved stack size for a Java thread is typically 1 MB (set with -Xss). It’s reserved up front, even if the thread only ever uses a few kilobytes.
  • Creation cost. Creating and destroying an OS thread means a system call and kernel bookkeeping. That’s why we pool threads instead of creating one per task.
  • Context switching. When the OS swaps one thread off a core and another on, it saves and restores registers and state in the kernel. With thousands of threads, a noticeable share of CPU time goes into switching instead of working.
  • A hard ceiling. In practice a server can run a few thousand OS threads comfortably. Not millions.

The thread-per-request model

Most Java web servers (Tomcat behind Spring MVC, for example) use thread-per-request: each incoming HTTP request gets one thread from a pool, and that thread handles it from start to finish. Tomcat’s default maximum is 200 threads.

This model is lovely to program. Your code reads top to bottom:

// Java · OrderController.java (classic, blocking style)
Order getOrder(long id) {
    Customer customer = customerRepository.findById(id);   // waits for the database
    List<Item> items  = inventoryClient.itemsFor(id);      // waits for another service
    return new Order(customer, items);
}

Stack traces make sense, debuggers work, exceptions go where you expect.

The problem: threads that wait still hold their OS thread

Look at where the time goes in a typical request. A few milliseconds of real CPU work, then 50 or 100 milliseconds waiting: for the database, for another HTTP service, for a file. During that wait the platform thread is blocked. And because it’s bound to its OS thread, the OS thread is blocked too. It can’t serve anyone else.

Three timelines for one request with 5 ms of work, a 100 ms database wait, then 5 ms of work. Platform thread: the OS thread is shown hatched in red as blocked for the whole wait. Virtual thread: the wait is a dashed empty box labelled unmounted, its stack waits on the heap. Carrier #1: during that same wait the OS thread runs many other coloured blocks, each a different virtual thread.
During a database call, a platform thread holds its OS thread idle. A virtual thread steps off, and the OS thread runs other work. Illustrative timings.

So the limit on a busy service usually isn’t CPU. It’s the number of threads. With 200 threads and requests that each wait about 100 ms, you top out near 2,000 requests per second, while the CPU sits mostly idle. This is Little’s law at work: requests in flight = throughput × time per request. If time per request is fixed by the database, the only way to raise throughput is more requests in flight, which means more threads, which OS threads can’t give you cheaply.

The workaround: asynchronous code

The industry’s answer was to stop blocking. CompletableFuture, reactive libraries like Project Reactor and RxJava, and Spring WebFlux all let a small number of threads juggle many requests by never waiting: you register a callback and hand the thread back.

// Java · the same logic, reactive style
Mono<Order> getOrder(long id) {
    return customerRepository.findById(id)
        .zipWith(inventoryClient.itemsFor(id))
        .map(t -> new Order(t.getT1(), t.getT2()));
}

It scales very well. But you pay for it: every library has to be non-blocking, code is written as chains of operators, stack traces show framework internals instead of your code, and debugging gets hard. Many teams found the cost too high and stayed with blocking code and big thread pools.

So Java developers had to choose: simple code that doesn’t scale, or scalable code that isn’t simple.

What virtual threads change

A virtual thread is a java.lang.Thread that is managed by the JVM, not bound to an OS thread. It’s still a real Java thread: it has a stack, a name, ThreadLocals, and it shows up in thread dumps. What’s different is where it runs.

Mounting, unmounting and carrier threads

The JVM keeps a small pool of platform threads called carrier threads (by default, a ForkJoinPool with about one carrier per CPU core). To run a virtual thread, the JVM mounts it on a carrier. The carrier’s OS thread executes the virtual thread’s code.

The key moment is what happens when the virtual thread blocks:

  1. Your code calls something blocking: a JDBC query, an HTTP call, Thread.sleep, reading a socket.
  2. The JDK notices the virtual thread is about to wait. Instead of blocking the OS thread, it unmounts the virtual thread: its stack frames are saved on the Java heap.
  3. The carrier is now free and immediately runs another virtual thread.
  4. When the database answers, the waiting virtual thread is scheduled again and mounted on a carrier (not necessarily the same one), and continues from the exact line where it stopped.

From your code’s point of view, nothing happened: the method call simply returned. The waiting still exists, but it no longer costs an OS thread.

Back to the restaurant: a waiter now drops the order at the kitchen, takes other tables, and anyone free brings the food out when it’s ready. Same 200 waiters, far more customers.

“Virtual threads don’t make waiting faster. They make waiting cheap.”

Why they are so cheap

  • Small, growable stacks. A virtual thread’s stack lives on the heap as chunks that grow and shrink with use. A fresh virtual thread costs a few hundred bytes to a few kilobytes, not a reserved megabyte.
  • No kernel involvement to create or switch. Mounting and unmounting are JVM operations, much cheaper than an OS context switch.
  • So you can have millions. Creating one virtual thread per task, even per tiny task, is fine. You don’t pool them.
Platform thread (before) Virtual thread (Java 21)
Backed by Its own OS thread, for life Any carrier thread, only while running
Stack Reserved up front (often ~1 MB) On the heap, grows as needed
Practical count Thousands Millions
When it blocks on I/O OS thread blocked too Unmounts; carrier runs other work
Pool it? Yes, they’re expensive No, create one per task
Programming style Plain blocking code Same plain blocking code

Writing virtual threads in Java 21

The API is deliberately small. You already know most of it.

// Java 21 · creating virtual threads
Thread vt = Thread.ofVirtual().name("order-worker").start(() -> handle(request));

Thread.startVirtualThread(() -> handle(request));      // shortcut

Thread.currentThread().isVirtual();                     // true inside a virtual thread

In application code you’ll mostly use the executor, which starts a new virtual thread for every submitted task:

// Java 21 · VirtualThreadsDemo.java
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
    IntStream.range(0, 10_000).forEach(i ->
        executor.submit(() -> fetchOrder(i)));          // each task: ~1 s of blocking I/O
}   // close() waits for all tasks to finish

A quick measurement

I ran exactly that: 10,000 tasks, each blocking for one second with Thread.sleep to stand in for a slow database call, on Java 21.

Executor Time to finish 10,000 tasks
Executors.newFixedThreadPool(200) (platform threads) about 50 s
Executors.newVirtualThreadPerTaskExecutor() about 1.1 s

The arithmetic explains it. 200 threads can only wait for 200 things at once, so 10,000 one-second waits take 10,000 ÷ 200 = 50 rounds. With virtual threads, all 10,000 wait at the same time on a handful of carriers. Your numbers will differ by machine, but the shape won’t.

In Spring Boot

From Spring Boot 3.2 on, running on Java 21, one property switches request handling (Tomcat and Jetty), @Async tasks and several other executors to virtual threads:

spring.threads.virtual.enabled=true

Your controllers and repositories don’t change.

What virtual threads do not do

They don’t make CPU-heavy code faster. If a task spends its time calculating (image resizing, encryption, big loops), it needs a core the whole time, and there are still only as many cores as before. Virtual threads help when tasks wait. For CPU-bound work, a platform thread pool sized to your cores is still right.

They don’t make one request faster. A single request still takes as long as its database call. What improves is throughput: how many requests you can handle at once.

They don’t remove downstream limits. If your database pool has 20 connections, 10,000 virtual threads will queue for those 20. That’s fine, but limit concurrency on purpose. Since you don’t pool virtual threads any more, use a Semaphore instead of a small pool:

// Java 21 · cap calls to a fragile service at 20 at a time
private final Semaphore permits = new Semaphore(20);

String callPartner(int id) throws InterruptedException {
    permits.acquire();
    try {
        return partnerClient.fetch(id);
    } finally {
        permits.release();
    }
}

Pitfalls to know in Java 21

Pinning. In some cases a virtual thread can’t unmount while it blocks, so it stays pinned to its carrier and blocks the carrier’s OS thread, just like old times. In Java 21 the main cause is blocking inside a synchronized block or method (or inside native code). If that happens often, carriers run out and throughput collapses. The usual fix in Java 21 is to use ReentrantLock instead of synchronized around blocking calls. You can spot pinning with the JFR event jdk.VirtualThreadPinned. (Java 24 removed the synchronized limitation with JEP 491, but if you’re on 21, plan for it.)

Don’t pool them. A pool of virtual threads brings back the limit you were trying to remove. Create one per task and let them die.

Go easy on ThreadLocal. Each virtual thread has its own copies. With a million threads, a heavyweight object cached in a ThreadLocal becomes a million objects. Caching expensive objects per thread was a platform-thread habit; drop it.

Check your libraries. Most modern JDBC drivers and HTTP clients work well, but older ones that block inside synchronized code will pin. Upgrading drivers is often the first step.

When to use virtual threads

Use them for work that spends most of its time waiting: web requests, calls to databases and other services, message consumers, file and network I/O. That covers most business applications.

Keep platform threads for CPU-bound work and anything that needs a fixed, small number of long-lived threads.

Key takeaways

  • Before Java 21, every Java thread was a platform thread, bound one to one to an expensive OS thread for its whole life.
  • Blocking I/O kept that OS thread busy doing nothing, so servers ran out of threads long before they ran out of CPU.
  • The old workaround, reactive / async code, scaled but made code harder to write, read and debug.
  • A virtual thread runs on a carrier thread only while it has work. When it blocks, it unmounts and the carrier runs another one.
  • Result: plain blocking code with far higher throughput for I/O-heavy work. Not faster CPU work, and not faster single requests.
  • In Java 21, watch for pinning in synchronized blocks, don’t pool virtual threads, and use a Semaphore to limit concurrency.

Frequently asked questions

What is a virtual thread in Java 21?

A lightweight Thread managed by the JVM instead of the operating system. Many virtual threads share a small pool of OS-backed carrier threads, and a virtual thread gives up its carrier whenever it blocks.

What is the difference between a platform thread and a virtual thread?

A platform thread is bound to one OS thread for its whole life and holds it even while waiting. A virtual thread only uses an OS thread while it’s actually running, so thousands or millions can exist at once.

Are virtual threads faster than normal threads?

Not for raw computation. They give better throughput for tasks that wait on I/O, because waiting no longer ties up an OS thread.

Do I need to rewrite my code to use virtual threads?

Usually not. Code written in the normal blocking style runs on virtual threads as is. You change how threads are created (an executor or a Spring Boot property), not the business logic.

Should I still use reactive programming?

If you have it and it works, there’s no rush to remove it. For new I/O-heavy services, virtual threads give similar scalability with simpler, blocking-style code, which is why many teams now start there.

Next in Modern Java: records, the one-line way to write data classes.

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.