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

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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • The Magic of Quarkus With Vert.x in Reactive Programming
  • Demystifying Java's Compare-and-Swap (CAS)
  • The Long Road to Java Virtual Threads
  • Java 21 Is a Major Step for Java: Non-Blocking IO and Upgraded ZGC

Trending

  • How to Build Local LLM RAG Apps With Ollama, DeepSeek-R1, and SingleStore
  • Scalable, Resilient Data Orchestration: The Power of Intelligent Systems
  • Stateless vs Stateful Stream Processing With Kafka Streams and Apache Flink
  • A Developer's Guide to Mastering Agentic AI: From Theory to Practice
  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
23.3K 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

  • The Magic of Quarkus With Vert.x in Reactive Programming
  • Demystifying Java's Compare-and-Swap (CAS)
  • The Long Road to Java Virtual Threads
  • Java 21 Is a Major Step for Java: Non-Blocking IO and Upgraded ZGC

Partner Resources

×

Comments

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: