This page is about blocking code in Vert.x that will block the event loop.
By default, blocking code is executed on the Vert.x worker pool.
promise can be composed, the database start first, then the web server.
@Override
public void start(Promise<Void> promise) throws Exception {
Future<Void> steps =
prepareDatabase()
.compose(v -> startHttpServer());
steps.setHandler(promise);
}
@Test
public void testRemoteInfo(TestContext context) {
Async async = context.async();
// async test code
async.awaitSuccess(5000);
}
All the plugin of vertx are asynchronous but when starting an application you may want to stay on the main thread and to wait for an execution. You want to perform the operations in sequence.
Example:
Solution:
System.out.println("Waiting for single event");
long tid = awaitEvent(h -> vertx.setTimer(1000, h));
System.out.println("Single event has fired");
To not block the main thread with blocking code such as a remote call (JDBC,…), you can use the executeBlocking function
vertx.<String>executeBlocking(future -> {
// Do the blocking operation in here
// Imagine this was a call to a blocking API to get the result
try {
Thread.sleep(500);
} catch (Exception ignore) {
}
String result = "armadillos!";
future.complete(result);
}, res -> {
if (res.succeeded()) {
system.out.println(res.result());
} else {
res.cause().printStackTrace();
}
});