Table of Contents

Vertx - Future Example

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.

Example:

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