简体   繁体   English

如何结合两个ListenableFutures并从第一个中获得结果以完成

[英]How combine two ListenableFutures and get the result from the first one to complete

Is there a simple way (library provided) to combine two com.google.common.util.concurrent.ListenableFuture and get the result from the first one to complete. 有没有简单的方法(提供的库)来组合两个com.google.common.util.concurrent.ListenableFuture并从第一个结果中获取结果即可完成。

Something like a coalesce in time: 有点像时间的融合

ListenableFuture f1 = ...;
ListenableFuture f2 = ...;
ListenableFuture f3 = Future.firstToComplete(f1,f2)

I guess this would be the equivalent to CompletionStage. 我想这相当于CompletionStage。 applyToEither : applyToEither

f3 = f1.applyToEither(f2, res->res);

Sounds like you want to use Futures.inCompletionOrder and simply wait for the first future in the list. 听起来好像您想使用Futures.inCompletionOrder并仅等待列表中的第一个Futures.inCompletionOrder

Once the first future completes, you will likely want to cancel() all the remaining futures in the list, but there is a (mostly benign) race there where the futures could be completing while you're cancelling them; 一旦第一个期货完成,您可能会想要cancel()列表中所有剩余的期货,但是那里有一场(主要是良性的)比赛,您可以在取消期货时完成该期货。 it depends on how close the finish is. 这取决于完成程度。 In the worst case, you might end up doing all the work for all the other futures anyway, but if your primary concern is latency and not the underlying work items, that's likely not going to be an issue for you. 在最坏的情况下,您可能最终还是要为所有其他期货完成所有工作,但是,如果您最关注的是延迟而不是底层工作项,那么这对您来说就不会成为问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM