@backstreetbrogrammer
--------------------------------------------------------------------------------
Chapter 02 - Virtual Threads based OMS
--------------------------------------------------------------------------------
The main difference with using traditional threads is that virtual threads do NOT entail any OS-level blocking.
Code snippet:
while (!serverSocket.isClosed()) {
final var socket = serverSocket.accept(); // blocks and socket can never be null
Thread.startVirtualThread(
() -| handle(socket, clientCounter.addAndGet(1))); // create a new virtual thread to handle request
}
When a virtual thread invokes join on a thread that is still running, it does not block the underlying OS thread, which continues to run other virtual threads.
In effect, the OS threads jump from code to code when using higher-order methods on futures, and they do so in a familiar programming style.
Because they are lightweight, virtual threads are also cheap to create and don't need to be pooled.
This also has a big advantage that if there are many client requests being received at the same time - virtual threads will be able to handle it proving much better throughput.
However, there is one drawback:
- Order must be thread-safe again and needs to be constructed first, before the validation, enrichment and persistence tasks are started.
This can be avoided by bringing back futures but having the futures run by virtual threads.
Github: github.com/backstreetbrogramm...
- Upgrade to Java 21 Playlist: • Upgrade to Java 21
- Apache Spark for Java Developers Playlist: • Apache Spark for Java ...
- Top Java Coding Interview Problems Playlist: • Top Java Coding Interv...
- Java Serialization Playlist: • Java Serialization
- Dynamic Programming Playlist: • Dynamic Programming
#java #javadevelopers #javaprogramming
Негізгі бет Ғылым және технология 15 - Virtual Threads based OMS
Пікірлер