VirtualThread
Virtual threads are lightweight threads managed by a runtime environment or a virtual machine. They are managed at the language level rather than at the operating system level. Introduced in Java 19 and finalized in Java 21, virtual threads offer significant improvements in handling concurrency.
Traditional Threads -> one-to-one mapping with native threads
Virtual Threads -> many-to-one mapping with native threads
If any blocking happens for a Java thread, it will block the operating system thread itself, causing the OS thread to be wasted and stay idle.
But the change made with virtual threads emphasizes that there is no one-to-one mapping.
Suppose a thread is using an OS thread for its execution and, due to some reason, it gets blocked, perhaps due to an IO operation or a third-party API call. In traditional threads, this would block the OS thread as well. But in the case of virtual threads, it will not keep locking the OS thread; instead, it will free the OS thread to execute other virtual threads.
In this way, proper utilization of OS threads can be achieved. Using this approach, we can create thousands of virtual threads to run concurrently, which was nearly impossible with standard threads.
Efficient Context Switching: The JVM can suspend and resume virtual threads efficiently, making context switching less costly compared to platform threads.
Scalability: Because they are lightweight, virtual threads scale much better, enabling high-concurrency applications.
Simplified Concurrency: Developers can write code in a straightforward, sequential style without the complexity of asynchronous programming, and still achieve high performance and scalability.
When to avoid virtual thread