Java 8 Multiple CompletableFutures

In previous posts, we have concept of how to use CompletableFutures. This tutorial is about combining multiple CompletableFutures, it is one of the most important and useful abilities of Java 8 asynchronous processing.

Related articles:
Java Future
CompletableFutures
CompletableFuture Handle Exception

I. Usage
1. thenCompose()

thenCompose() can chain 2 CompletableFutures by using the result which is returned from the invoking future.

combinedFuture uses thenCompose() method of future with calculateCF function to get and modify the result from previous step of future.

Run the code, the Console shows:

2. thenCombine()

thenCombine() combines two futures when they are both done, it is different from thenCompose() which chains a new future only when the first future is done.

Run the code, the Console shows:

3. thenAcceptBoth()

thenAcceptBoth() is just like thenCombine(), but not return a CompletableFuture.

Run the code, the Console shows:

4. acceptEither()

Use testAcceptEither() when we just need the faster result of one of them.

Run the code, the Console shows:

5. allOf()

allOf() gets list of futures and waits all of the input futures done to complete itself.

Run the code, the Console shows:

6. anyOf()

anyOf() is opposite to allOf(), it just waits any input future done to complete itself.

Run the code, the Console shows:

II. Source code

MultiCompletableFuture

By JavaSampleApproach | December 17, 2016.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*