我一直在使用CompletableFuture.allOf(...)
帮助器创建聚合期货,只有当它们的组合期货被标记为完成时才会“完成”,即:
CompletableFuture<?> future1 = new CompletableFuture<>();
CompletableFuture<?> future2 = new CompletableFuture<>();
CompletableFuture<?> future3 = new CompletableFuture<>();
CompletableFuture<?> future = CompletableFuture.allOf(future1, future2, future3);
我希望此功能略有不同,在以下情况下,总体未来是完整的市场:
- 所有期货均已成功完成OR
- 任何一个未来都已失败完成
在后一种情况下,聚合 future 应该(例外地)立即完成,而不必等待其他 future 完成,即快速失败.
为了说明这一点,与CompletableFuture.allOf(...)
考虑一下:
// First future completed, gotta wait for the rest of them...
future1.complete(null);
System.out.println("Future1 Complete, aggregate status: " + future.isDone());
// Second feature was erroneous! I'd like the aggregate to now be completed with failure
future2.completeExceptionally(new Exception());
System.out.println("Future2 Complete, aggregate status: " + future.isDone());
// Finally complete the third future, that will mark the aggregate as done
future3.complete(null);
System.out.println("Future3 Complete, aggregate status: " + future.isDone());
Using allOf(...)
,这段代码产生:
Future1 Complete, aggregate status: false
Future2 Complete, aggregate status: false
Future3 Complete, aggregate status: true
而我的替代聚合实现将在功能 2 完成后返回“true”,因为它是一个例外。
我在 Java 标准库中找不到任何可以帮助我实现这一目标的实用程序,这感觉很奇怪……因为它是一个相对普通的用例。
看看实施情况CompletableFuture.allOf(...)
很明显,这些场景背后的逻辑相当复杂。我不想自己写这个,我想知道是否有其他选择?