How to Run Blocking Code in Vert.x
Want to learn how to run blocking code in Vert.x? Check out this post to learn more about blocking code and synchronous APIs.
Join the DZone community and get the full member experience.
Join For FreeAs mentioned in the introduction article, Vert.x has a golden role: don’t block the event loop. To be honest, usually we work with synchronous APIs and many of the methods are likely to block. Hence, in some cases, we can't avoid waiting for a result of our thread. For example, this includes when creating a database connection, writing data to disk, or executing a query, as well as many other situations. Well, does Vert.x have a solution for such situations?
Running Blocking Code
Vert.x provides two ways to use traditional blocking APIs safely within a Vert.x application. One of these ways is the executeBlocking
method, which executes the blocking code and specifies a result handler to be called back asynchronous when the blocking code has been executed.
vertx.executeBlocking(future -> {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILE_PATH_AND_NAME))){
writer.write("Hello");
} catch (Exception ex) {
log.error("Failed to save word {} ", ex);
}
future.complete();
}, res -> {
System.out.println("The word was written");
});
In this way, you can run inline blocking code directly while on an event loop. By default, blocking code is executed on the Vert.x worker pool. Its configuration can be customized according to your needs through the DeploymentOptions
object with the setWorkerPoolSize
. For example, if you set the worker pool size to 100, then Vert.x will use this pool to run blocking code. Also, Vert.x allows additional pools to be created for different purposes.
WorkerExecutor executor = vertx.createSharedWorkerExecutor("my-file-write-worker-pool");
executor.executeBlocking(future -> {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILE_PATH_AND_NAME))){
writer.write("Hello");
} catch (Exception ex) {
log.error("Failed to save word {} ", ex);
}
future.complete();
}, res -> {
System.out.println("The word was written");
});
When it’s no longer necessary, the worker executor must be closed.
executor.close();
Running inline blocking code can be enough in some cases, but to take full advantage of the code encapsulate advantage and for clean code, in most cases, it would be more useful to use the worker verticles.
Worker Verticles
Worker Verticles are similar to standard verticles. The only difference is the use of a thread from the worker pool as distinct from the standard verticles. Hence, the worker verticles won't block any event loops.
To deploy a verticle as a worker you do setsetWorker
to true
through DeploymentOptions
.
public static void main(String[] args){
final Vertx vertx = Vertx.vertx();
final DeploymentOptions options = new DeploymentOptions().setWorker(true)
.setWorkerPoolSize(DEFAULT_WORKER_POOL_SIZE);
vertx.deployVerticle(new WorkerVerticle(), options, res -> {
if (res.succeeded()) {
log.info("Deployment id is: " + res.result());
} else {
log.info("Deployment failed!");
}
});
}
That is all.
Conclusion
Vert.x doesn't want the event loop to be blocked because of its asynchronous architecture, but we usually work with synchronous APIs by necessarily in many cases. Fortunately, Vert.x provide two ways that they are inline, and the worker verticle uses traditional blocking APIs safely within a Vert.x application for these situations. For clean code and to take full advantage of the encapsulation, I think it is more accurate to use worker verticles in many cases. You can be found a simple example of worker verticle on this link.
References
Opinions expressed by DZone contributors are their own.
Comments