vertx-examples
vertx-examples copied to clipboard
Sharing vertx instance?
I was getting an NPE when referring to a vertx instance in one of the 2 verticles, so I did this:
public static void main( String[] args ) {
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfiguration.class);
final Vertx vertx = Vertx.vertx();
vertx.deployVerticle(new SpringVerticle(vertx,context));
vertx.deployVerticle(new MainVerticle(vertx));
System.out.println("Deployment done");
}
whereas the example in the project is like so:
public static void main( String[] args ) {
ApplicationContext context = new AnnotationConfigApplicationContext(ExampleSpringConfiguration.class);
final Vertx vertx = Vertx.vertx();
vertx.deployVerticle(new SpringDemoVerticle(context));
vertx.deployVerticle(new ServerVerticle());
System.out.println("Deployment done");
}
using the second example, how does the vertx instance get shared? is it basically a global?
the Null Pointer Exception I was getting was here:
public SpringVerticle(final ApplicationContext ctx) {
this.service = (UserService) ctx.getBean("userService");
this.pool = vertx.createSharedWorkerExecutor( // !! NPE BOMB fml ... vertx is null
"my-worker-pool",
Pool.poolSize,
Pool.maxExecuteTime,
Pool.maxExecuteTimeUnit
);
}
so I had to change it to:
public SpringVerticle(final Vertx vertx, final ApplicationContext ctx) {
this.service = (UserService) ctx.getBean("userService");
this.vertx = vertx;
this.pool = vertx.createSharedWorkerExecutor(
"my-worker-pool",
Pool.poolSize,
Pool.maxExecuteTime,
Pool.maxExecuteTimeUnit
);
}
kinda weird TBH
No it's not a "global".
Whenever verticles are deployed, the init
method is called, and sets vertx
attribute.
https://github.com/eclipse-vertx/vert.x/blob/master/src/main/java/io/vertx/core/AbstractVerticle.java#L66
This allows you to instantiate stuff as you need to, especially if your verticle doesn't have a default constructor, hence Vert.x cannot instantiate it, then pass it to Vert.x so that it goes through "the verticle lifecycle" (init, start, ...).
ok i see, so i guess the fix i have works well enough?
I'd have moved the this.pool =
within init
, so that you can leave the constructor without Vertx
parameter.