Java Virtual Threads
Java Virtual Threads were introduced in Java 19 as a preview and as a second preview in Java 20. And are included in Java 21 as a permanent feature.
They enable us to create as many threads as we want without depending upon the platform threads. Although they run on platform threads only, we can create as many threads as we want.
Virtual Threads uses a Continuation class from Java which is not exposed as a public API, i.e., it is used by classes which are included in JDK only. It makes use of Continuation.yield() and Continuation.run(). The Continuation.yield() method is called when Java detects that there is an I/O blocking operation and transfers the Virtual Thread to Heap Memory. When the I/O blocking operation continues Java calls Continuation.run(), which will enable Virtual Threads to run after extracting it from the Heap Memory by transferring it to the platform thread again and the Thread will continue to run again.
It is recommended that we should not use Virtual Threads when there is no I/O blocking operation during the execution.
Synchronized code where the execution time is too high should also avoided as it will cause a Pinning issue, i.e., it will pin the Virtual Thread to the platform thread(worker thread).
Hope you have got the basic idea of Virtual Threads in Java.
Thanks for reading.
Interested in supporting? Ko-Fi