Back
Close

Building a HTTP Endpoint with Eclipse Vert.x

cescoffier
9,046 views
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();
vertx.createHttpServer()
.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());
req.response()
.putHeader("Content-Type", "application/json; charset=UTF8")
.end(json.encodePrettily());
})
.listen(8080);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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.

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants