Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CompletableFuture already completed with an exception

Tags:

CompletableFuture.completedFuture() returns a CompletedFuture that is already completed with the given value.

How do we construct a CompletableFuture that is already completed exceptionally?

Meaning, instead of returning a value I want the future to throw an exception.

like image 834
Gili Avatar asked Mar 05 '18 18:03

Gili


People also ask

What happens when CompletableFuture throws exception?

If the completable future was completed successfully, then the logic inside “exceptionally” will be skipped. For example, given a failed future with exception “Oops” which normally returns a string, we can use exceptionally to recover from failure.

What does CompletableFuture complete do?

complete() is an instance method of the CompletableFuture class that completes the future with the passed value if the future has not been completed already.

How do you handle exceptions in runAsync?

Method isCompletedExceptionally() can be used to determine if a CompletableFuture completed in any exceptional fashion. In case of exceptional completion with a CompletionException , methods get() and get(long, TimeUnit) throw an ExecutionException with the same cause as held in the corresponding CompletionException .

Is CompletableFuture get blocking?

It just provides a get() method which blocks until the result is available to the main thread. Ultimately, it restricts users from applying any further action on the result. You can create an asynchronous workflow with CompletableFuture. It allows chaining multiple APIs, sending ones to result to another.


2 Answers

Unlike Java 9 and later, Java 8 does not provide a static factory method for this scenario. The default constructor can be used instead:

CompletableFuture<T> future = new CompletableFuture<>(); future.completeExceptionally(exception); 
like image 148
Gili Avatar answered Oct 05 '22 20:10

Gili


Java 9 provides CompletableFuture.failedFuture​(Throwable ex) that does exactly that.

like image 40
Didier L Avatar answered Oct 05 '22 21:10

Didier L