简体   繁体   English

等待每个CompletableFuture完成

[英]Wait for every CompletableFuture to complete

What I am trying to do is calculate the depth of a tree structure asynchronously, I will have the first level of the tree and I want to kick off an asynchronous thread to calculate the depth of each of the nodes separately. 我想做的是异步计算树结构的深度,我将拥有树的第一层,我想启动一个异步线程来分别计算每个节点的深度。

During the course of the calculations there might obviously be a fork in the tree, at which point I want to kick of an additional thread to calculate that branch. 在计算过程中,显然树中可能存在一个分支,这时我想踢一个额外的线程来计算该分支。

I have got this working pretty much however I need to do some finishing up logic when all of these futures have completed. 我已经完成了很多工作,但是当所有这些期货都完成后,我需要做一些整理逻辑。 But I am having trouble with the additional CompletableFutures that are spawned along the way. 但是我在沿途产生的其他CompletableFutures遇到了麻烦。

What method would I use to save up all of the starting CompletableFutures + the ones that are dynamically created along the way and have a way to await all of them to complete before doing any additional logic. 我将使用哪种方法来保存所有开始的CompletableFutures和在此过程中动态创建的方法,并有一种方法可以等待所有方法完成后再执行任何其他逻辑。

You can try to get a value from each CompletableFuture. 您可以尝试从每个CompletableFuture中获取一个值。 If a value is available check for the next one. 如果有一个值,请检查下一个。 If it is not available the executions stops for the current value before checking the next one. 如果不可用,则在检查下一个值之前停止执行当前值。 You can do with a code similar to the following: 您可以使用类似于以下代码的代码:

List<CompletableFuture<Integer>> myList = ...
for (CompletableFuture<Integer> c: myList) {
   Integer x = c.get();
   ...
}
// You arrive here only when all the CompletableFuture have returned a 
// value.

Hard to say without known the specific use case or some code but you could use an external AtomicInteger to keep the track of the deep length. 在不知道特定用例或某些代码的情况下很难说,但是您可以使用外部AtomicInteger来跟踪深度。 Something like: 就像是:

CompletableFuture<Whatever> doStuff(..., int deep) {
  if(getCurrentDeep() < deep) setDeep(deep);
  // ...
  CompletableFuture<Whatever> stuff1 = doStuff(..., deep + 1);
  CompletableFuture<Whatever> stuff2 = doStuff(..., deep + 1);

  return stuff1.thenCombine(stuff2, (s1, s2) -> /* merge stuff */ )
}

In the other hand, would be much better if you could use an Actor library as Akka or Vertx to follow this approach. 另一方面,如果可以使用Actor库作为Akka或Vertx来遵循这种方法,那就更好了。

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

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