AllOf and anyOf can combine any number of CompletableFutures. The function interface definition is shown below.
First, both of these functions are static functions whose arguments are collections of variable-length CompletableFutures. Secondly, the difference between allOf and anyOf, the former is “and”, the latter is “or”.
Case 1: allOf
The return value of allOf is of type CompletableFuture. This is because each CompletableFuture that is passed in May have a different return value, so the result of the combination cannot be represented by a type. Instead, Void is returned. So, how do you get the execution result of each CompletableFuture?
See the example below: download 100 web pages in parallel. After downloading, count the number of pages containing a word in 100 pages.
The key issue here is that since Allof does not return a value, attach a callback function to allFutures via theApply. Inside the callback, call a Future’s Get() function, Get 100 results, store them to the List
The next step is to count the number of pages containing the word [XXX] in the 100 pages
Example 2: anyOf
AnyOf means that as long as any CompletableFuture finishes, you can do the next thing instead of waiting for all completableFutures to finish, as AllOf does.
But since the return type of each CompletableFuture can be different, any one of them, which means you can’t tell what type, anyOf’s return value is of type CompletableFuture. Consider the following example.
In this case, because the return value of future1, future2, and future3 is CompletableFuture, anyOf must also return an Object of type String.
And of the three futures, Future2 has the shortest sleep time and will be executed first. AnyOfFuture. Get () gets the content of Future2. The results of future1 and future3 are discarded
A review of the overall use of CompletableFuture can be summarized in the following points
- Simple use of get() and complete()
- Submit tasks runAsync() and supplyAsync()
- Chain theRun(), thenAccept(), and thenApply()
- Combination of thenCompose() and thenCombine(), allOf and anyOf()