@backstreetbrogrammer
--------------------------------------------------------------------------------
Chapter 02 - Virtual Threads with Futures OMS
--------------------------------------------------------------------------------
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.
Code snippet:
final var request = new Request(socket);
final var orderValidateFuture = new CompletableFuture|Order|();
final var orderEnrichFuture = new CompletableFuture|Order|();
final var orderPersistFuture = new CompletableFuture|Order|();
Thread.startVirtualThread(() -: orderValidateFuture.complete(ClientWallet.validate(request)));
Thread.startVirtualThread(() -: orderEnrichFuture.complete(MarketData.enrich(request)));
Thread.startVirtualThread(() -: orderPersistFuture.complete(OrderStatePersist.persist(request)));
new Order(request)
.validate(orderValidateFuture.join())
.enrich(orderEnrichFuture.join())
.persist(orderPersistFuture.join())
.sendToDownstream();
Virtual threads can significantly improve application throughput when:
- The number of concurrent tasks is high (more than a few thousand), and
- The workload is not CPU-bound, since having many more threads than processor cores cannot improve throughput in that case.
Virtual threads help to improve the throughput of typical server applications precisely because such applications consist of a great number of concurrent tasks that spend much of their time waiting.
Besides that, we should also consider a few other points while using virtual threads:
- there is no improvement in latency, but only throughput
- virtual threads are always daemon threads =: trying to set it to non-daemon will result in exception
- virtual threads should never be used as fixed-size thread pool
- virtual threads always have default priority =: trying to change the priority will cause no effect
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
Негізгі бет Ғылым және технология 16 - Virtual Threads with Futures OMS
Пікірлер