DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Python Async/Sync: Advanced Blocking Detection and Best Practices (Part 2)
  • Python Async/Sync: Understanding and Solving Blocking (Part 1)
  • The Magic of Quarkus With Vert.x in Reactive Programming
  • Demystifying Java's Compare-and-Swap (CAS)

Trending

  • Architecting Zero-Trust AI Agents: How to Handle Data Safely
  • Why Round-Robin Won't Save You: Load Balancing Challenges in Data Streaming Services With Heterogeneous Traffic
  • The Middleware Gap in AI Agent Frameworks
  • Building a Spring AI Assistant With MCP Servers: A Step-by-Step Tutorial
  1. DZone
  2. Software Design and Architecture
  3. Microservices
  4. How to Run Blocking Code in Vert.x

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.

By 
Hüseyin Akdoğan user avatar
Hüseyin Akdoğan
DZone Core CORE ·
Updated Oct. 08, 18 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
24.0K Views

Join the DZone community and get the full member experience.

Join For Free

As 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

  • Vert.x Core Manual for Java

Vert.x Blocking (computing)

Opinions expressed by DZone contributors are their own.

Related

  • Python Async/Sync: Advanced Blocking Detection and Best Practices (Part 2)
  • Python Async/Sync: Understanding and Solving Blocking (Part 1)
  • The Magic of Quarkus With Vert.x in Reactive Programming
  • Demystifying Java's Compare-and-Swap (CAS)

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook