Skip to content

Instantly share code, notes, and snippets.

@purplefox
Last active April 20, 2018 17:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save purplefox/7f464be396dfb04275ee075468eba823 to your computer and use it in GitHub Desktop.
Save purplefox/7f464be396dfb04275ee075468eba823 to your computer and use it in GitHub Desktop.
private void doIt() {
CompletableFuture<String> cf = execute(this::findBook);
// Now you have a CompletableFuture you can use it like any CompletableFuture
cf.whenComplete((s,t)-> {
// CF callbacks will be always be called on the correct Vert.x thread, no need to worry about
// fork-join pools or anything like that
});
}
// Some arbitrary blocking method which returns a String
// Could do a database operation, whatever. It is allowed to block.
private String findBook() {
return "a book";
}
// Boiler plate method to convert from your blocking method to a CompletableFuture
private <T> CompletableFuture<T> execute(Supplier<T> blockingMethod) {
CompletableFuture<T> cf = new CompletableFuture<T>();
vertx.executeBlocking(fut -> {
try {
T result = blockingMethod.get();
fut.complete(result);
} catch (Exception e) {
fut.fail(e);
}
}, (AsyncResult<T> ar) -> {
if (ar.succeeded()) {
cf.complete(ar.result());
} else {
cf.completeExceptionally(ar.cause());
}
});
return cf;
}
@fzakaria
Copy link

fzakaria commented Apr 20, 2018

@purplefox

CF callbacks can execute on the calling thread -- not necessarily where the original CF executed.

Here is a simple example:

public CompletableFuture<Void> write(RequestContext context) {
    Assertions.assertOnEventLoop();
    return new execute( () -> {
          Assertions.assertOnWorkerThread();
          //do some work
    }).thenRun( () -> {
          //This assertion can fail!
         Assertions.assertOnWorkerThread(); 
         //do some work
     });
}

If the original CF is complete by the time the callback is executed, it is performed on the client calling thread.
(https://www.nurkiewicz.com/2015/11/which-thread-executes.html)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment