To my understanding one of the reasons to switch to a reactive (e.g. Project Reactor, RxJava, Vert-X) or actor (Akka) framework is because of the cost of thread switching is high. Looking at Difference between platform thread, carrier thread and virtual thread in context of Java 21 and later and other information about virtual threads I was wondering…
Do Virtual Threads remove reason to switch to a different paradigm because it will just swap out the blocking virtual thread to a different thread on the carrier?
>Solution :
Yes.
Platform threads in Java are mapped directly to a thread host operating system thread. Those OS threads are “expensive” in terms of memory and CPU.
Virtual threads, in contrast, are managed within the JVM, and extremely “cheap” meaning they are quite efficient in both memory and CPU. Now with virtual threads, you can reasonable expect to run even millions of tasks simultaneously on common computer hardware.
Yes, most , if not all, of the work done as reactive code can be done instead with Java virtual threads. The coding is vastly simpler to write, comprehend, trace, and debug. Reactive approach was invented to get around the performance problems of over-using platform threads. Making reactive programming unnecessary was one of the major motivations for inventing virtual threads.
Caveat… Virtual threads are contra-indicated for tasks that are CPU-bound such as video encoding/decoding. Use virtual threads only for code that involves blocking, such logging, file I/O, accessing databases, network calls.
For details, see firstly the official document, JEP 444: Virtual Threads. Then see the more recent videos of presentations by Ron Pressler, Alan Bateman, or José Paumard.
If you really want to understand how the impressive performance gains were made, see the talk by Ron Pressler on Continuations. To be clear: This understanding is entirely optional, unnecessary to making effective use of virtual threads. But if you need to satisfy your geek curiosity, you’ll enjoy that particular talk by Pressler.