Video in progress

How do virtual threads in Java 21 work internally, and when do they really help?

A virtual thread is a lightweight thread managed by the JVM: on a blocking operation it "steps off" the carrier (platform) thread, its stack is saved to the heap, and the carrier picks up other work. The benefit comes in services with a lot of IO waiting and thousands of concurrent requests, not in CPU-bound work.

📖 Answer

A platform thread is a wrapper around an OS thread: each has roughly 1 MB of stack (virtual memory), and creating one and switching between them is expensive. Opening 10,000 of them is hard.

Virtual threads run on a scheduler based on a ForkJoinPool, and by default the number of carriers equals the number of CPU cores. When a thread blocks in something like socket.read(), Thread.sleep or BlockingQueue.take:

  1. the JDK code notices this and unmounts the thread, so its stack frames are copied to the heap;
  2. the carrier is freed and picks up another virtual thread;
  3. when the IO is ready, the virtual thread is mounted again on some carrier.
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    for (Order o : orders) {
        executor.submit(() -> paymentClient.charge(o));   // a separate thread for each
    }
}   // close() waits for everything to finish

Where it helps: services where a request spends most of its time waiting for a DB, HTTP or Kafka response. You write plain blocking-style code with no reactive framework and still get high concurrency. In Spring Boot 3.2+, with spring.threads.virtual.enabled=true, Tomcat and @Async move to them.

Where it doesn't help:

  • CPU-bound computation: the number of carriers is still the number of cores;
  • when the bottleneck is a downstream (20 connections in the DB): 10,000 virtual threads just wait for those same 20;
  • pinning: in Java 21, blocking inside synchronized holds on to the carrier.

Don't pool virtual threads. They're cheap, so you create a new one per task. If you need to limit them, use a Semaphore.