Java 如何在Vertx事件循环线程上运行CompletableFuture处理程序?

Java 如何在Vertx事件循环线程上运行CompletableFuture处理程序?,java,java-8,reactive-programming,vert.x,completable-future,Java,Java 8,Reactive Programming,Vert.x,Completable Future,我有一个库xyz,它为我提供了一个完整的未来,我想在我的Vertx(v3.5)事件循环中处理它。目前我正在使用(见下文),但我想使用,但我不知道如何将vertx事件循环线程提供给此方法调用中的第二个参数 我尝试在中执行整个代码,但handleAsync中的调用仍然在Java的ForkJoin池中执行,我希望避免这种情况 CompletableFuture<Void> f = xyz.someMethod(); f.handle((v, th) -> { //Want to ru

我有一个库xyz,它为我提供了一个完整的未来,我想在我的Vertx(v3.5)事件循环中处理它。目前我正在使用(见下文),但我想使用,但我不知道如何将vertx事件循环线程提供给此方法调用中的第二个参数

我尝试在中执行整个代码,但handleAsync中的调用仍然在Java的ForkJoin池中执行,我希望避免这种情况

CompletableFuture<Void> f = xyz.someMethod();
f.handle((v, th) -> { //Want to run this in handleAsync()
   if (th == null) {
     future.complete(null);
   } else {
     future.completeExceptionally(th);
   }
   return null;
});
CompletableFuture f=xyz.someMethod();
f、 handle((v,th)->{//要在handleAsync()中运行此操作
如果(th==null){
future.complete(空);
}否则{
未来。完全例外(th);
}
返回null;
});

这可以通过以下方法完成。这是一种变通办法,而不是最佳解决方案。最初,我将runOnContext调用放在handle方法之外,这就是它不起作用的原因

CompletableFuture f=xyz.someMethod();
f、 句柄((v,th)->{
Vertex.runOnContext(e->{
如果(th==null){
future.complete(空);
}否则{
未来。完全例外(th);
}
});
返回null;
});


这将产生一个额外的上下文切换(从ForkJoin池到vertx事件循环),这是这种方法的一个缺点

只需使用
vertx.nettyEventLoopGroup()
作为第二个参数即可实现这一点,因此您的代码如下所示:

CompletableFuture<Void> f = xyz.someMethod();
f.handleAsync((v, th) -> { 

  if (th == null) {
    future.complete(null);
  } else {
    future.completeExceptionally(th);
  }

  return null;
}, vertx.nettyEventLoopGroup());
CompletableFuture f=xyz.someMethod();
f、 handleAsync((v,th)->{
如果(th==null){
future.complete(空);
}否则{
未来。完全例外(th);
}
返回null;
},vertx.nettyEventLoopGroup());
注意:上述代码可能会在Vertx future运行的同一线程上运行回调代码

要保留Vertx的线程模型,需要使用以下代码:

CompletableFuture<String> f = xyz.someMethod();
Context context = vertx.getOrCreateContext();
f.handleAsync((v, th) -> {
    context.runOnContext(event -> {
        if (th == null) {
            future.complete(null);
        } else {
            future.completeExceptionally(th);
        }
    });
    return null;
});
CompletableFuture f=xyz.someMethod();
Context Context=vertx.getOrCreateContext();
f、 handleAsync((v,th)->{
context.runOnContext(事件->{
如果(th==null){
future.complete(空);
}否则{
未来。完全例外(th);
}
});
返回null;
});

Wow。谢谢。我不知道这是存在的。最好是handleAsync,因为这是我们需要的,需要两个参数;您已经将vertx.nettyEventLoopGroup()作为f.handle()的第二个参数编写,该参数不可编译,因为f.handle不接受两个参数。因此,请将其更正为f.handleAsync()。