首页 > 解决方案 > 处理 Future#get 和 InterruptedException 声纳 java:S2142

问题描述

在我继承的一些遗留代码中,有一个与此类似的片段。

List<Callable<String>> callableStrings = Arrays.asList("one", "two", "three").stream()
        .map(s -> (Callable<String>) () -> s)
        .collect(Collectors.toList());

List<String> results =
        someExecutorService.invokeAll(callableStrings).stream()
                .map(
                        future -> {
                            try {
                                return future.get();
                            } catch (ExecutionException | InterruptedException e) {
                                LOG.info("Unexpected Exception encountered while fetching result", e);
                                return null;
                            }
                        })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

而不是Callable<String>,我真的在处理一些更繁重的计算。Sonar 将 突出显示catch (ExecutionException | InterruptedException e)为一个问题,建议您始终重新抛出InterruptedException. https://rules.sonarsource.com/java/tag/multi-threading/RSPEC-2142

这段代码的意图似乎是过滤掉任何有问题的繁重计算,只返回那些成功的。对于上下文,此代码是作为我的应用程序正在处理的 HTTP 请求的结果调用的。如果InterruptedException允许一直传播到顶部,那么客户端将获得错误响应,而不是看到成功结果的列表。

在处理InterruptedExceptionfrom时可以找到许多不同类型的信息Future#get。大多数看起来非常清晰和可靠的建议是那些正在处理您已经实现类似并从该类Runnable中调用的情况的建议。Future#get

这个答案https://stackoverflow.com/a/4268994表明,如果我InterruptedException在上面的代码中看到抛出,这表明处理 HTTP 请求的线程已被中断,而不是运行 Future 的线程。那是对的吗?

我的问题是:

标签: javaconcurrencyinterrupted-exception

解决方案


推荐阅读