Tech Interview RoomStudy guides

Advanced Java

What are virtual threads, when should you use them and what are the pitfalls?

Advanced · 2 min read · Lesson 6 of 10 in Advanced Java

What they are

Virtual threads (Java 21, JEP 444) are Thread instances managed by the JVM rather than the OS. Many virtual threads are multiplexed onto a small pool of carrier (platform) threads, a ForkJoinPool sized to the CPU count. When a virtual thread blocks on I/O, sleep, a lock or a BlockingQueue, the JVM unmounts it (saving its stack to the heap) and the carrier runs another virtual thread.

Why it matters

The thread-per-request model stays simple and debuggable (normal stack traces, ThreadLocal, blocking APIs) but scales to hundreds of thousands of concurrent blocked requests, which previously needed reactive programming. Creating one costs about a microsecond and a few hundred bytes to a few KB.

When to use

  • High-concurrency, I/O-bound work: REST services calling databases and other services, fan-out calls, message consumers.
  • In Spring Boot 3.2+: spring.threads.virtual.enabled=true runs Tomcat request handling, @Async and scheduling on virtual threads.

When not to, and pitfalls

  • No speedup for CPU-bound work; there are still only Ncpu carriers.
  • Do not pool them; create one per task (Executors.newVirtualThreadPerTaskExecutor()).
  • Pinning: before JDK 24, blocking inside a synchronized block or native call pins the virtual thread to its carrier, so a few pinned threads can stall everything. JDK 24 (JEP 491) removed pinning for synchronized; on Java 21 prefer ReentrantLock in hot paths and diagnose with -Djdk.tracePinnedThreads=full or JFR's jdk.VirtualThreadPinned event.
  • Downstream limits still apply: 50,000 virtual threads hitting a 20-connection pool simply queue on the pool. Limit concurrency with a Semaphore, not with a thread pool.
  • Large ThreadLocal values multiplied by a million threads cost memory; consider ScopedValue.

Example

java
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    List<Future<Price>> prices = suppliers.stream()
        .map(s -> executor.submit(() -> s.quote(sku)))     // each blocking HTTP call gets its own virtual thread
        .toList();
    return prices.stream().map(Future::resultNow).min(comparing(Price::amount)).orElseThrow();
}

Follow-up questions interviewers ask

Try answering each one before you open it.

Virtual threads or reactive (WebFlux)?

Both solve the "too many blocked threads" problem. Virtual threads keep imperative code, normal debugging and the blocking JDBC ecosystem, which suits most business services. Reactive still has advantages for streaming (back-pressure, SSE, WebSockets) and composing many event streams, but it is harder to write, debug and onboard. For a new Spring MVC service on Java 21, virtual threads are usually the pragmatic choice.

What is structured concurrency?

A preview API (StructuredTaskScope) that treats a group of concurrent subtasks as one unit: they are forked inside a scope, and the scope does not exit until all complete. Policies such as "shut down on first failure" cancel the siblings automatically, so threads never leak and errors propagate cleanly. It pairs naturally with virtual threads for fan-out calls.