Building a HTTP Endpoint with Eclipse Vert.x

cescoffier
2,397 views

Open Source Your Knowledge, Become a Contributor

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

Create Content

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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.

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