我试图在CompletableFuture中链接任务,以并行执行它们,并获得最佳的性能和资源利用率。
我正在编写的工作流有五个阶段,每个阶段取决于前几个阶段的结果。
工作流执行如下:
* Stage-1: Create CustomerContext -> This will call downstream services and return Context object.
* Stage-2: Generate Candidates for the customer -> This stage generate candidates and returns a List<Candidate> object. This stage requires CustomerContext as a parameter to generate the candidates.
* Stage-3: Process Candidate -> In this stage I process the candidates and returns processed List<Candidate>. This stage requires CustomerContext and List<Candidate> object from stage-1 and stage-2
* Stage-4: Rank candidates -> In this stage I perform candidate ranking and returns ranked List<Candidate> object. This stage requires CustomerContext and List<Candidate> object from stage-1 and **stage-3**
* Stage-5: Generate Result -> In this stage I generate the final result and returns Result object by making downstream API calls., This stage requires CustomerContext and List<Candidate> object from **stage-1** and **stage-4** 我可以创建一个结果持有者对象来保存每个阶段的结果。不过,我不知道这是否最好的解决办法。
CompletableFuture是这个用例的最佳解决方案吗?将这些阶段链接起来的最佳方式是什么?
发布于 2022-07-08 08:58:12
使用thenCompose组合来自相互依赖的不同期货的结果:
CompletableFuture<String> result =
CompletableFuture.supplyAsync(() -> "result 1")
.thenCompose(result1 ->
CompletableFuture.supplyAsync(result1::length)
.thenCompose(strLen ->
CompletableFuture.supplyAsync(strLen::toString)));但是请注意,由于每个未来都依赖于前一个结果,因此无法并行执行它们。每个未来仍将执行后,上一个已经完成。如果期货不相互依赖,您可以通过"unearthing the hidden applicative"并行运行它们。
还要注意的是,CompletableFuture只允许supplyAsync和runAsync分别使用Supplier和Runnable,而且也没有直接处理可能引发异常的异步操作的方法(例如运行Callable)。如果您需要这样做,您就必须像描述的in this answer那样将它委托给一个助手未来。
https://stackoverflow.com/questions/72907385
复制相似问题