首页 > 解决方案 > 在可完成的未来失败中传播信息

问题描述

我正在使用可完成的期货来做很多事情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);
    }

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

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

我的问题是,我不仅想知道它是否失败,还想知道其他元数据,例如value导致失败的元数据。我的希望是可能有一个我可以分析的异常对象。值得注意的是,例外checked exception (interrupt).

标签: javamultithreadingcompletable-future

解决方案


这将是我的建议:

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

推荐阅读