Combining via allOf()

Let's assume that we want to download the following list of invoices:

List<String> invoices = Arrays.asList("#2334", "#122", "#55");

This can be seen as a bunch of independent tasks that can be accomplished in parallel, so we can do it using CompletableFuture as follows:

public static CompletableFuture<String> 
downloadInvoices(String invoice) {

return CompletableFuture.supplyAsync(() -> {
logger.info(() -> "Downloading invoice: " + invoice);

return "Downloaded invoice: " + invoice;
});
}

CompletableFuture<String> [] cfInvoices = invoices.stream()
.map(CustomerAsyncs::downloadInvoices)
.toArray(CompletableFuture[]::new);

At this point, we have an array of CompletableFuture instances, and, therefore, an array of asynchronous computations. Furthermore, we want to run all of them in parallel. This can be accomplished using the allOf​(CompletableFuture<?>... cfs) method. The result consists of a CompletableFuture<Void> as follows:

CompletableFuture<Void> cfDownloaded 
= CompletableFuture.allOf(cfInvoices);
cfDownloaded.get();

Obviously, the result of allOf() is not very useful. What can we do with CompletableFuture<Void>? There are definitely many problems when we need the results of each computation involved in this parallelization, so we need a solution for fetching the results instead of relying on CompletableFuture<Void>.

We can solve this problem via thenApply() as follows:

List<String> results = cfDownloaded.thenApply(e -> {
List<String> downloaded = new ArrayList<>();

for (CompletableFuture<String> cfInvoice: cfInvoices) {
downloaded.add(cfInvoice.join());
}

return downloaded;
}).get();
The join() method is similar to get(), but, if the underlying CompletableFuture completes exceptionally, it throws an unchecked exception .

Since we are calling join() after all the involved CompletableFuture have completed, there is no blocking point.

The returned List<String> contains the results obtained by calling the downloadInvoices() method as follows:

Downloaded invoice: #2334

Downloaded invoice: #122

Downloaded invoice: #55
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.51.153