java - 在可完成的未来失败中传播信息
问题描述
我正在使用可完成的期货来做很多事情X
。X
与互联网对话,可能会失败也可能不会失败。当我调用时,X
我给它传递了一个值,我们称之为它value
。X(value)
.
private void X(String value) {
CompletableFuture<Boolean> future = CompletableFuture.supplyAsync(()-> {
try {
Object response = talkToExternalThing(value);
} catch (InterruptedException e) {
throw new CompletionException(e.getCause());
}
return true;
}).exceptionally(ex -> false);
futures.add(future);
}
以上是我正在玩的一个片段。在分析结果集时,我可以看到在我的测试中失败/未失败的所有值(即真或假)。
Map<Boolean, List<CompletableFuture<Boolean>>> result = futures.stream()
.collect(Collectors.partitioningBy(CompletableFuture::isCompletedExceptionally));
我的问题是,我不仅想知道它是否失败,还想知道其他元数据,例如value
导致失败的元数据。我的希望是可能有一个我可以分析的异常对象。值得注意的是,例外是checked exception (interrupt)
.
解决方案
这将是我的建议:
ExecutorService executorService = Executors.newCachedThreadPool();
private void X(String value) {
CompletableFuture<Pair<Boolean, String>> future = new CompletableFuture<>();
executorService.execute(() -> {
try {
Object response = talkToExternalThing(value);
} catch (InterruptedException e) {
// un-successfully, with the value
future.complete(new Pair<>(false, value));
return;
}
// successfully, with the value
future.complete(new Pair<>(true, value));
});
futures.add(future);
}
推荐阅读
- java - 处理 LocalDate 和 Months 名称
- excel - #N/A 在 Excel 中使用 vlookup
- javascript - Array.prototype.includes 中的错误?
- node.js - npm test -- --coverage 永远不会退出
- android - 如何从纬度和经度按升序对距离进行排序
- javascript - 为什么状态总是为 0,即使在使用 useCallback 之后
- hyperledger-fabric - Fabric 中组织的“PeerAdmin”和“Admin”有什么区别?
- html - 错误消息更改所有块的宽度。如何解决?
- sql - 获取分组后用户的所有数据
- machine-learning - 需要帮助选择损失函数