如何使java.util.concurrent.Future失败

问题描述 投票:1回答:1

qzxswpoi在vertx生态系统中有相当多的使用:io.vertx.core.Future

使用Vertx https://vertx.io/docs/apidocs/io/vertx/core/Future.html的一个例子如下:

Future

我的印象是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有关,但它似乎没有。正如您所看到的,告诉Vertx未来失败的方法是调用它的fail()方法。

另一方面,我们有CompletableFuture,它是java.util.concurrent.Future接口的一个实现:java.util.concurrent.Future

我没有在CompletableFuture上看到失败方法,我只看到“resolve()”。

所以我的猜测是,使CompletableFuture失败的唯一方法是抛出异常?

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html

除了抛出错误,有没有办法“失败”CompletableFuture?换句话说,使用Vertx Future,我们只调用f.fail(),但是对于CompletableFuture呢?

java vert.x completable-future
1个回答
1
投票

CompletableFuture<String> f = CompletableFuture.supplyAsync(() -> { throw new RuntimeException("fail this future"); return "This would be the success result"; }); 鼓励你从CompletableFuture方法中抛出异常来描述失败。

正如评论中所提到的那样,还有supplyAsync()方法,你可以使用它,以防你手头有completeExceptionally(),并希望失败。

Future

从Java9开始,如果你想返回一个已经失败的未来,那么还有https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#completeExceptionally-java.lang.Throwable-构造。

CompletableFuture.failedFuture​(Throwable ex)

© www.soinside.com 2019 - 2024. All rights reserved.