如何使java.util.concurrent.Future失败 [英] How to fail a java.util.concurrent.Future
问题描述
在vertx生态系统中大量使用 io.vertx.core.Future
:
> https://vertx.io/docs/apidocs/io/vertx/core/Future.html
There is pretty heavy use of io.vertx.core.Future
in the vertx ecosystem:
https://vertx.io/docs/apidocs/io/vertx/core/Future.html
使用Vertx Future
的示例在此处:
An example of using Vertx Future
is here:
private Future<Void> prepareDatabase() {
Future<Void> future = Future.future();
dbClient = JDBCClient.createShared(vertx, new JsonObject(...));
dbClient.getConnection(ar -> {
if (ar.failed()) {
LOGGER.error("Could not open a database connection", ar.cause());
future.fail(ar.cause()); // here
return;
}
SQLConnection connection = ar.result();
connection.execute(SQL_CREATE_PAGES_TABLE, create -> {
connection.close();
if (create.failed()) {
future.fail(create.cause()); // here
} else {
future.complete();
}
});
});
return future;
}
我的印象是 io.vertx。 core.Future
与 java.util.concurrent.Future
有关,但似乎没有。如您所见,告诉Vertx未来失败的方法是调用它的fail()方法。
I was under the impression that io.vertx.core.Future
had something to do with java.util.concurrent.Future
, but it appears that it doesn't. As you can see the way to tell a Vertx future to fail is to call it's fail() method.
另一方面,我们有CompletableFuture,它是 java.util.concurrent.Future
接口:
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html
On the other hand, we have CompletableFuture which is an implementation of the java.util.concurrent.Future
interface:
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html
我在CompletableFuture上看不到失败方法,我只看到 resolve()。
I don't see a fail method on the CompletableFuture, I only see "resolve()".
所以我的猜测是使CompletableFuture失败的唯一方法是抛出异常?
So my guess is that the only way to fail a CompletableFuture is to throw an Exception?
CompletableFuture<String> f = CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("fail this future");
return "This would be the success result";
});
除了抛出错误外,有没有办法使CompletableFuture失败?
换句话说,使用Vertx Future,我们只调用f.fail(),但是使用CompletableFuture怎么办?
besides throwing an error, is there a way to "fail" a CompletableFuture? In other words, using a Vertx Future, we just call f.fail(), but what about with a CompletableFuture?
推荐答案
CompletableFuture
鼓励您抛出 supplyAsync()
方法中的异常来描述失败。
CompletableFuture
encourages you to throw exceptions from supplyAsync()
method to describe failures.
如评论中所述,还有 completeExceptionally()
方法,如果您有将来
,并希望失败。
As mentioned in the comments, there's also completeExceptionally()
method, which you can use in case you have a Future
at hand, and would like to fail it.
自Java9以来,还有 CompletableFuture .failedFuture(throwable ex)
构造,如果您想返回已经失败的未来。
Since Java9, there's also CompletableFuture.failedFuture(Throwable ex)
construct, if you want to return an already failed future.
这篇关于如何使java.util.concurrent.Future失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!