Java / Java 21 Virtual Threads Interview questions
How do you migrate a thread-pool-based application to virtual threads?
Migration works best as a staged process rather than a blanket swap:
- Replace the outermost, request-facing
ExecutorService(e.g. a fixed thread pool) withExecutors.newVirtualThreadPerTaskExecutor(), since that's where the I/O-bound, high-fan-out benefit is greatest. - Audit code for pinning-prone patterns -
synchronizedblocks wrapping blocking calls, and JNI/native code paths. - Re-check any artificial backpressure that relied on a small pool size; downstream systems like a database connection pool still have real limits, so add an explicit
Semaphoreor similar bound instead of relying on thread scarcity. - Run with
-Djdk.tracePinnedThreads=fullunder representative load to catch pinning regressions early. - Benchmark under production-like concurrency and load before rolling out broadly.
Migrating incrementally, one executor at a time, makes it much easier to attribute any regression to a specific change.
More Related questions...