How to fail a java.util.concurrent.Future

坚强是说给别人听的谎言 提交于 2019-12-24 17:08:31

问题


There is pretty heavy use of io.vertx.core.Future in the vertx ecosystem: https://vertx.io/docs/apidocs/io/vertx/core/Future.html

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;
}

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.

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

I don't see a fail method on the CompletableFuture, I only see "resolve()".

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";
});

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?


回答1:


CompletableFuture encourages you to throw exceptions from supplyAsync() method to describe failures.

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.

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#completeExceptionally-java.lang.Throwable-

Since Java9, there's also CompletableFuture.failedFuture​(Throwable ex) construct, if you want to return an already failed future.

https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/CompletableFuture.html#failedFuture-java.lang.Throwable-



来源:https://stackoverflow.com/questions/54757857/how-to-fail-a-java-util-concurrent-future

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!