vertx-examples icon indicating copy to clipboard operation
vertx-examples copied to clipboard

Sharing vertx instance?

Open ORESoftware opened this issue 5 years ago • 3 comments

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

ORESoftware avatar Jan 27 '19 06:01 ORESoftware

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, ...).

aesteve avatar Jan 27 '19 14:01 aesteve

ok i see, so i guess the fix i have works well enough?

ORESoftware avatar Jan 27 '19 19:01 ORESoftware

I'd have moved the this.pool = within init, so that you can leave the constructor without Vertx parameter.

aesteve avatar Jan 28 '19 07:01 aesteve