Java / Java 21 Interview Questions
What are Virtual Threads in Java 21 and how do they differ from Platform Threads?
Virtual Threads (JEP 444) are lightweight threads managed by the JVM rather than the operating system. A platform (OS) thread maps 1:1 to a kernel thread and consumes roughly 1–2 MB of stack memory each, limiting practical concurrency to a few thousand threads per JVM. Virtual threads are multiplexed over a small pool of carrier (platform) threads by the JVM scheduler, consuming only a few hundred bytes of heap per thread, enabling millions of concurrent threads in the same process.
| Aspect | Platform Thread | Virtual Thread |
|---|---|---|
| Managed by | OS kernel | JVM (Project Loom) |
| Memory (stack) | ~1–2 MB each | ~few hundred bytes (heap) |
| Max practical count | Thousands | Millions |
| Blocking I/O | Blocks OS thread | Parks virtual thread; carrier thread freed |
| Creation | Thread / ExecutorService | Thread.ofVirtual() / Executors.newVirtualThreadPerTaskExecutor() |
// Creating a virtual thread directly
Thread vt = Thread.ofVirtual().name("my-vt").start(() -> {
System.out.println("Running on: " + Thread.currentThread());
});
// Per-task executor — one virtual thread per submitted task
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 100_000).forEach(i ->
executor.submit(() -> {
Thread.sleep(Duration.ofMillis(100)); // parks, not blocks carrier
return i * i;
}));
} // executor.close() waits for all tasksWhen a virtual thread blocks on I/O or Thread.sleep(), the JVM parks it (saves its continuation to the heap) and reassigns the carrier thread to another runnable virtual thread — no OS thread is held idle. This is fundamentally different from reactive/async programming: you write simple blocking code and the JVM handles the event-loop-like scheduling transparently.
Key constraints: Synchronized blocks pin the virtual thread to its carrier (no parking during a synchronized block). Use java.util.concurrent.locks.ReentrantLock instead of synchronized in hot paths to avoid pinning. Thread-locals work but can cause high memory usage at scale — prefer Scoped Values (JEP 446).
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
