Building a HTTP Endpoint with Eclipse Vert.x


Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content
Previous: Getting query parameters Next: Summary

Observing the event loop

Things are going to be a bit more interesting now... Let's modify our code to print in the JSON response the name of the thread handling the request and the current date:

Observing the event loop
package io.vertx.playground;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
public class HttpServerEventLoopExample {
public static void main(String... args) {
Vertx vertx = Vertx.vertx();
.requestHandler(req -> {
String name = req.getParam("name");
String message = "hello " + (name != null ? name : "world") + "!";
JsonObject json = new JsonObject()
.put("message", message)
.put("time", System.currentTimeMillis())
.put("thread", Thread.currentThread().getName());
.putHeader("Content-Type", "application/json; charset=UTF8")

Try to invoke the server several times. Notice it's always the same thread handling your request.

Vert.x uses very few threads, and some of them are event loops. The only purpose of the event loop is to get incoming "events" (here HTTP requests), find the interested Handler (here the request handler) and invoke it. This is a very simple execution model simplifying concurrency (you are always called by the same thread). However... it comes with a golden rule: Never block the event loop. The reason is simple. If a Handler blocks the event loop, the incoming events would be enqueued in a buffer and would only be processed when the blocking handler release the thread. You would loose the advantage of the event loop and making you application sloppy. So don't block the event loop.

The event loop

How to achieve this? Vert.x provides a large set of APIs all asynchronous and non-blocking. It also provides constructs to handle blocking code, but this would be covered in another tutorial.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content