java - 处理 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
允许一直传播到顶部,那么客户端将获得错误响应,而不是看到成功结果的列表。
在处理InterruptedException
from时可以找到许多不同类型的信息Future#get
。大多数看起来非常清晰和可靠的建议是那些正在处理您已经实现类似并从该类Runnable
中调用的情况的建议。Future#get
这个答案https://stackoverflow.com/a/4268994表明,如果我InterruptedException
在上面的代码中看到抛出,这表明处理 HTTP 请求的线程已被中断,而不是运行 Future 的线程。那是对的吗?
我的问题是:
- 我应该关注声纳警告吗?如果是的话,保持代码不变会发生什么坏事?
- 代码应该如何重构才能改进?
解决方案
推荐阅读
- wordpress - 字体未显示在我的 WordPress 网站中。我用@font-face直接在css中添加
- java - 如何检测已接电话?
- mysql - 使用所有已配置的数据库/表设置 MySQL(主从)复制
- installshield - InstallShield "Full" Redistributable 强制互联网访问
- css - 为什么将谓词应用于 xpath 中的字符串是有效的?
- xml - 如何将 xs:occurs 属性组添加到我的元素声明中?
- jquery - SharePoint 2013 - GridView 上的 jQuery
- .net - .NET ASMX WebService 和客户端调用的外部类
- cumulocity - 在 cumulocity 托管的自定义应用程序中存储托管对象的位置
- windows - 适用于 Windows 10 的 Thingworx 客户端