CompletableFuture
CompletableFuture can be used to wait for an execution finish in test fixtures or preparation.
Don't use it in a Vertx verticle execution, otherwise, you will block the event loop and therefore the execution.
CompletableFuture<Void> testDataLoaded = new CompletableFuture<>();
vertx
.executeBlocking(AppTest::loadTestData) // load test data
.onFailure(t -> {
Logger.error(t);
testDataLoaded.complete(null);
})
.onSuccess(appLoaded::complete);
try {
// wait, we make it wait because the class can be extended
// and the extension needs that the verticle has been deployed
testDataLoaded.get(60, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
Logger.error(e);
}
Future Composition
With composition, the operations run concurrently.
- Future.join
- waits until all futures are completed, either with a success or a failure.
- succeeded when all the futures are succeeded,
- failed when all the futures are completed and at least one of them is failed
- Future.all
- waits until all futures are successful or one fails,
- succeeded when all the futures are succeeded
- failed when at least one of the futures is failed
- Future.any composition
- waits for the first succeeded future.
- succeeded if at least one is succeeded
- failed when all failed
Example:
- Future.all
Future.all(futures)
.onComplete(ar -> {
if (!ar.succeeded()) {
cause = ar.cause();
// ...
return;
}
for (int i = 0; i < futures.size(); i++) {
result = ar.result().resultAt(0);
// ...
}
});
- Future Join
Future.join(futures)
.onComplete(ar -> {
CompositeFuture compositeResult = ar.result();
for (int i = 0; i < futures.size(); i++) {
if (compositeResult.failed(i)) {
Throwable cause = compositeResult.cause(i);
// ...
} else {
result = compositeResult.resultAt(i);
}
}
});