firstthumb
firstthumb

Reputation: 4744

Does Vertx 3 support CompletableFuture?

I want to develop my application promise style using vertx and CompletableFuture fits really for this purpose but JVM uses fork/join on the background for CompletableFuture and this may break Vertx Thread Safety.

Do you have any idea or have used this feature on your project?

Upvotes: 4

Views: 4229

Answers (3)

mohamnag
mohamnag

Reputation: 2883

technically seen its always possible to do async operations on other threads that are not managed by Vertx and return the result to be consumed by Vertx managed thread. The key is to obtain a Context before starting the async operation using vertx.getOrCreateContext() and then using that to return the result when its ready.

Assuming you have a Handler<AsyncResult<>> of some kind, this can be a sample code:

public void doAsyncThing(String someParam, String otherParam, Handler<AsyncResult<Void>> resultHandler) {
    Context vertxContext = vertx.getOrCreateContext();
    CompletableFuture<Void> future = 
        someOperatinThatTriggersAsync(someParam, otherParam)
            .handleAsync((unused, throwable) -> {
                vertxContext.runOnContext(unused1 -> {
                    if (throwable == null) {
                      responseHandler.handle(Future.succeededFuture());
                    } else {
                      responseHandler.handle(Future.failedFuture(throwable));
                    }
                });
                return null;
          });
}

Upvotes: 1

adave
adave

Reputation: 41

There is also https://github.com/cescoffier/vertx-completable-future. From the README:

This project provides the Completable Future API but enforces the Vert.x threading model:

  • When using xAsync methods (without executor), the callbacks are called on the Vert.x context
  • When using non-async, it uses the caller thread. If it's a Vert.x thread the same thread is used. If not called from a Vert.x thread, it still uses the caller thread
  • When using xAsync methods with an Executor parameter, this executor is used to execute the callback (does not enforce the Vert.x thread system)

Haven't used yet, though.

Upvotes: 3

haschibaschi
haschibaschi

Reputation: 2792

Yes it does, here is an example http://qrman.github.io/posts/2015/08/28/callback_hell_completablefuture_ftw/

But I think JavaRx is the better solution because its supported as first class citizen by vert.x http://vertx.io/docs/vertx-rx/java/

Upvotes: 2

Related Questions