Last active
April 20, 2018 17:10
-
-
Save purplefox/7f464be396dfb04275ee075468eba823 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@purplefox
CF callbacks can execute on the calling thread -- not necessarily where the original CF executed.
Here is a simple example:
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)