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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  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.

Hüseyin Akdoğan user avatar by
Hüseyin Akdoğan
CORE ·
Oct. 08, 18 · Tutorial
Like (3)
Save
Tweet
Share
20.22K 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.

Popular on DZone

  • Top Five Tools for AI-based Test Automation
  • The Role of Data Governance in Data Strategy: Part II
  • Memory Debugging: A Deep Level of Insight
  • Why Does DevOps Recommend Shift-Left Testing Principles?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: