Java / Java 21 Virtual Threads Interview questions
How can you optimize an application to fully benefit from virtual threads?
Getting the full benefit of virtual threads takes more than swapping in a new executor - a handful of practices matter most:
- Never pool virtual threads - create one per task instead of reusing a fixed set.
- Replace synchronized with ReentrantLock around any code path that also performs a blocking call, to avoid pinning.
- Minimize ThreadLocal usage; prefer
ScopedValuefor passing context to child tasks. - Use structured concurrency (
StructuredTaskScope) to manage groups of related subtasks so none can leak. - Keep CPU-bound work off virtual threads, or at least be aware it doesn't parallelize beyond your core count.
- Isolate native/JNI calls onto a small dedicated pool of platform threads if they can't be made Loom-aware.
Applying these consistently is usually more impactful than any single configuration flag.
More Related questions...