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

时间:2018-03-11 10:41:26

标签: java java-8 reactive-programming vert.x completable-future

我有一个库xyz,它给了我一个CompletableFuture,我想在我的Vertx(v3.5)事件循环中处理它。目前我正在使用CompletableFuture.handle(BiFunction)(见下文),但我想使用CompletableFuture.handleAsync(BiFunction, Executor),但我无法弄清楚如何在此方法调用中将vertx事件循环线程提供给第二个参数。

我尝试在Vertx.runOnContext()中执行整个代码,但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;
});

2 个答案:

答案 0 :(得分:1)

您只需使用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());

答案 1 :(得分:0)

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

CompletableFuture<Void> f = xyz.someMethod(); f.handle((v, th) -> { vertx.runOnContext(e->{ if (th == null) { future.complete(null); } else { future.completeExceptionally(th); } }); return null; });

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