zaf*_*003 3 java reactive-programming java-8 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;
});
Run Code Online (Sandbox Code Playgroud)
您可以通过简单地使用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());
Run Code Online (Sandbox Code Playgroud)
注意:上面的代码可能会在与 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;
});
Run Code Online (Sandbox Code Playgroud)