在完全未来失败中传播信息



我使用可完成期货来做X的一堆事情。X与互联网对话,可以失败也可以不失败。当我调用X时,我会给它传递一个值,让我们称它为valueX(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);
}

上面是我正在玩的一个片段。当分析结果集时,我可以看到测试中所有失败/未失败的值(即true或false(。

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);

}

最新更新