在 completablefuture 失败中传播信息

Propagating information in completablefuture failure

我正在使用可完成的期货来做很多事情XX 与互联网对话,可以失败也可以不失败。当我调用 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);
    }

以上是我正在玩的片段。在分析结果集时,我可以看到 failed/didn 在我的测试中没有失败的所有值(即真或假)。

Map<Boolean, List<CompletableFuture<Boolean>>> result = futures.stream()
 .collect(Collectors.partitioningBy(CompletableFuture::isCompletedExceptionally));

我的问题是,我不仅想知道它是否失败,我还想知道其他元数据,例如导致失败的 value。我希望潜在地有一个异常对象,我可以作为结果进行分析。值得注意的是异常 a 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);
    
}