JDK 12 exceptionallyCompose()

User problem: Fetch a printer IP via the printing service or fallback to the backup printer IP. Or, generally speaking, when this stage completes exceptionally, it should be composed using the results of the supplied function applied to this stage's exception.

We have CompletableFuture that fetches an IP of a printer managed by the printing service. If the service is not responding then it throws an exception as follows:

CompletableFuture<String> cfServicePrinterIp 
= CompletableFuture.supplyAsync(() -> {

int surrogate = new Random().nextInt(1000);
if (surrogate < 500) {
throw new IllegalStateException(
"Printing service is not responding");
}

return "192.168.1.0";
});

We also have  CompletableFuture that fetches the IP of the backup printer:

CompletableFuture<String> cfBackupPrinterIp 
= CompletableFuture.supplyAsync(() -> {

return "192.192.192.192";
});

Now, if the printing service is not available, then we should rely on the backup printer. This can be accomplished via the JDK 12 exceptionallyCompose() as follows:

CompletableFuture<Void> printInvoice 
= cfServicePrinterIp.exceptionallyCompose(th -> {

logger.severe(() -> "Exception: " + th
+ " Thread: " + Thread.currentThread().getName());

return cfBackupPrinterIp;
}).thenAccept((ip) -> logger.info(() -> "Printing at: " + ip));

Calling printInvoice.get() may reveal one of the following results:

  • If the printing service is available:
[INFO] Printing at: 192.168.1.0
  • If the printing service is not available:
[SEVERE] Exception: java.util.concurrent.CompletionException ...
[INFO] Printing at: 192.192.192.192

For further parallelization, we can rely on exceptionallyComposeAsync().

..................Content has been hidden....................

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