14 - Futures with composition OMS

Опубликовано: 16 Июль 2026
на канале: Rishi’s programming channel
74
3

‪@backstreetbrogrammer‬

--------------------------------------------------------------------------------
Chapter 02 - Virtual Threads - Futures with composition OMS
--------------------------------------------------------------------------------

In Java, a thenCombine() method can be used to combine the results of two futures using a two-argument function.

CompletableFuture.completedFuture(new Order(request))
.thenCombine(orderValidateFuture, Order::validate)
.thenCombine(orderEnrichFuture, Order::enrich)
.thenCombine(orderPersistFuture, Order::persist)
.thenAccept(Order::sendToDownstream);

Time taken is same as before: 1 + max(1, 1, 1) + 1 = 3 seconds.

The handling thread creates a new order, as before, but wraps it in a future so that thenCombine can be called for validation, and then it calls again with the enrichment and persistence tasks.

Finally, a callback thenAccept() is used to send the order to downstream.

None of this code is blocking.

Pool threads jump from validation, enrichment and persistence tasks to order building and order sending, performing tasks as they become available, even across separate requests.

In this case, the only actual processing that the connection-handling thread performs is the building of a base order.


Github: https://github.com/backstreetbrogramm...

Upgrade to Java 21 Playlist:    • Upgrade to Java 21  
Apache Spark for Java Developers Playlist:    • Apache Spark for Java Developers  
Top Java Coding Interview Problems Playlist:    • Top Java Coding Interview Problems  
Java Serialization Playlist:    • Java Serialization  
Dynamic Programming Playlist:    • Dynamic Programming  

#java #javadevelopers #javaprogramming