What are virtual threads in Java, and when do they help?
BackendSenior
In shortVirtual threads are lightweight threads scheduled by the JVM onto a few carrier threads, so blocking code can scale to many thousands of concurrent requests. They help I/O-bound, thread-per-request code; they don't make CPU-bound work faster and don't remove limits like connection pools.
Model answer
How they work: a virtual thread is a Java object, not an OS thread. The JVM mounts it on a carrier (a platform thread from a small ForkJoinPool). When it blocks on I/O, sleep or a lock, it unmounts and the carrier runs another virtual thread. Millions can exist; creating one is cheap, so you create one per task and never pool them.
Where they help: classic thread-per-request servers (Spring MVC with spring.threads.virtual.enabled=true, JDBC, blocking HTTP clients) that spend most of their time waiting. You get much of the scalability of reactive code with straightforward, debuggable blocking code and normal stack traces.
What they don’t change:
- CPU-bound work runs at the same speed; there are still only as many cores.
- Downstream limits: a connection pool of 20 still means 20 concurrent queries; thousands of virtual threads just queue for it. Use semaphores to bound concurrency towards fragile dependencies.
- Pinning: before JDK 24, blocking inside
synchronizedpinned the carrier (JEP 491 removed most of that); native calls still pin. Diagnose withjdk.VirtualThreadPinnedJFR events. - ThreadLocal-heavy code multiplies memory with millions of threads; prefer scoped values where possible.
Compared with alternatives: reactive stacks still fit streaming and backpressure-heavy systems; Kotlin coroutines offer structured concurrency at the language level. For typical CRUD services, virtual threads are the simplest way to raise concurrency.
What they're looking for
How they work (mounting on carriers, unmounting on blocking), where they help, pinning and its causes, limits that still apply (pools, rate limits), ThreadLocal costs, and comparison with reactive code and Kotlin coroutines.
Common mistakes
- Pooling virtual threads.
- Expecting CPU-bound code to speed up.
- Ignoring that a 10-connection pool still allows only 10 concurrent queries.
More backend questions
- What is the N+1 query problem, and how do you find and fix it?Mid-level
- What does Spring Boot's auto-configuration do, and how do you change what it set up?Mid-level
- How does a Spring backend authenticate requests from a mobile app, and how do you make sure users only see their own data?Mid-level
- Your Spring Boot service in Kubernetes keeps restarting with exit code 137. How do you investigate and fix it?Senior