Vert.x - Blocking Code

About

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.

How to

executing block of code in sequence

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

wait asynchronous execution in test

@Test
public void testRemoteInfo(TestContext context) {
	Async async = context.async();

	// async test code 

	async.awaitSuccess(5000);
}

execute blocking code

Synchronously

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:

  • when you read a configuration with configRetriever
  • and that you want to integrate it in the lifecycle hooks of the launcher, you need to retrieve the configuration before deploying a verticle.

Solution:

System.out.println("Waiting for single event");
long tid = awaitEvent(h -> vertx.setTimer(1000, h));
System.out.println("Single event has fired");

Asynchronously

To not block the main thread with blocking code such as a remote call (JDBC,…), you can use the executeBlocking function

Example from vert-x3/vertx-examples/blob/master/core-examples/src/main/java/io/vertx/example/core/execblocking/ExecBlockingExample.java

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

Powered by ComboStrap