Reputation: 605
I am new to Java and vertx. In creating a vertx-web PoC, I chose instance properties on my handlers as an easy way to share data in a futures chain because of callbacks. Looking at my code someone asked if my implementation was multi-threaded. I started reading more docs and came across event-loop/worker threads and standard/worker/multi-thread verticles. This then mutated into wondering about concurrent calls.
In providing a handler to Route.handler() does a new TestHandler get instantiated for every request or does handler create a singleton on the Route and TestHandler bar shared for concurrent requests?
If it is a singleton. How could i handle concurrency? More instances on the vertx deployment? Stateless Handler classes?
Java examples and articles seem to use demonstrate things in a very simple context and leaves any implementation to be coupled with a working knowledge of advanced concepts. This has been making learning Java very difficult. Any help/tips/advice for a new Java dev would be much appreciated.
Application.java
public class Application {
public static void main(String[] args) {
Vertx vertx = Vertx.vertx();
vertx.deployVerticle("com.foo.testServer");
}
}
TestServer.java
public class TestServer extends AbstractVerticle {
@Override
public void start() {
Router router = Router.router(vertx);
router.post("/test").handler(new TestHandler());
vertx.createHttpServer().requestHandler(router).listen(8000);
}
}
TestHandler.java
public class TestHandler implements Handler<RoutingContext> {
private String bar;
// ... other future methods
public void handle(@NotNull RoutingContext ctx) {
bar = ctx.getBodyAsJson().getString("bar");
// ... future method calls
ctx.response().setStatusCode(200).end(bar);
}
}
Upvotes: 0
Views: 910
Reputation: 20699
Usually in vert.x instances of Handler
, Promise
and Future
are singletons and are instantiated on once-per-verticle-instance basis.
As soon as they are supposed to be thread-safe (pure functional, no shared-state), they can be used in multi-threaded environments by default.
Upvotes: 0
Reputation: 9128
The purpose of Vert.x is to be able to handle a lot of concurrent requests with very few threads, using non-blocking APIs.
Indeed, when you deploy a verticle, an event loop is assigned to the instance and a single thread will handle the events. This is by design and it relieves the developer from thinking about complex multi-threading issues.
Then of course modern hardware often provides multiple cores. In this case, you can deploy multiple instances of your verticle. You will still benefit from the single-threaded development model and also take advantage of all the CPU cores.
More on this in the Reactor and Multi-Reactor section of the Vert.x core docs.
Upvotes: 1