I'd like to create a CompletableFuture
that has already completed exceptionally.
Scala provides what I'm looking for via a factory method:
Future.failed(new RuntimeException("No Future!"))
Is there something similar in Java 10 or later?
The CompletableFuture. get() method is blocking. It waits until the Future is completed and returns the result after its completion.
As such, there's nothing you can do through CompletableFuture to interrupt any thread that may be running some task that will complete it. You'll have to write your own logic which tracks any Thread instances which acquire a reference to the CompletableFuture with the intention to complete it.
runAsync. Returns a new CompletableFuture that is asynchronously completed by a task running in the given executor after it runs the given action.
What is CompletableFuture? A CompltableFuture is used for asynchronous programming. Asynchronous programming means writing non-blocking code. It runs a task on a separate thread than the main application thread and notifies the main thread about its progress, completion or failure.
I couldn't find a factory method for a failed future in the standard library for Java 8 (Java 9 fixed this as helpfully pointed out by Sotirios Delimanolis), but it's easy to create one:
/**
* Creates a {@link CompletableFuture} that has already completed
* exceptionally with the given {@code error}.
*
* @param error the returned {@link CompletableFuture} should immediately
* complete with this {@link Throwable}
* @param <R> the type of value inside the {@link CompletableFuture}
* @return a {@link CompletableFuture} that has already completed with the
* given {@code error}
*/
public static <R> CompletableFuture<R> failed(Throwable error) {
CompletableFuture<R> future = new CompletableFuture<>();
future.completeExceptionally(error);
return future;
}
Java 9 provides CompletableFuture#failedFuture(Throwable)
which
Returns a new
CompletableFuture
that is already completed exceptionally with the given exception.
that is more or less what you submitted
/**
* Returns a new CompletableFuture that is already completed
* exceptionally with the given exception.
*
* @param ex the exception
* @param <U> the type of the value
* @return the exceptionally completed CompletableFuture
* @since 9
*/
public static <U> CompletableFuture<U> failedFuture(Throwable ex) {
if (ex == null) throw new NullPointerException();
return new CompletableFuture<U>(new AltResult(ex));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With