IntStream 何时真正关闭?SonarQube S2095 是 IntStream 的误报吗?

When is an IntStream actually closed? Is SonarQube S2095 a false positive for IntStream?(IntStream 何时真正关闭?SonarQube S2095 是 IntStream 的误报吗?)

本文介绍了IntStream 何时真正关闭?SonarQube S2095 是 IntStream 的误报吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Java 8 流代替许多旧样式的 for 循环来迭代一堆结果并生成汇总统计信息.例如:

I am using Java 8 streams in place of many old style for loops to iterate through a bunch of results and produce summary statistics. For example:

int messages = IntStream.rangeClosed(0, 7).map(ids::get).reduce(Integer::sum).getAsInt();

注意:我知道还有其他方法可以进行上面显示的计数.我这样做是为了说明我的问题.

我正在使用带有 Java 3.9 插件的 SonarQube 5.3.在该配置中,上面的代码行违反了 squid 规则 S2095:资源应该关闭."这就是我希望看到 AutoCloseable(例如 FileInputStream)是否已打开但从未关闭的结果.

I am using SonarQube 5.3 with the Java 3.9 plugin. In that configuration, the above line of code gives me a violation of squid rule S2095: "Resources should be closed." That's the result I would expect to see if an AutoCloseable (e.g., a FileInputStream) was opened but never closed.

所以这是我的问题:终端操作 reduce 是否关闭流?应该是?或者这是鱿鱼规则中的误报?

So here's my question: does the terminal operation reduce close the stream? Should it? Or is this a false positive in the squid rule?

推荐答案

它没有关闭,因为 AutoCloseable 接口只在 try-with-resources 内部工作.但是正如 AutoCloseable 接口 javadoc 中所说的那样,对于 IntStream 来说,这种关闭操作是完全没有必要的:

It isn't closed, because AutoCloseable interface works only inside try-with-resources. But this close operation is totally unnecessary for IntStream as it said in AutoCloseable interface javadoc:

但是,当使用 java.util.stream.Stream 等工具时,支持基于 I/O 和非基于 I/O 的形式,try-with-resources使用非基于 I/O 的表单时,通常不需要块.

However, when using facilities such as java.util.stream.Stream that support both I/O-based and non-I/O-based forms, try-with-resources blocks are in general unnecessary when using non-I/O-based forms.

所以是的 S2095 是 IntStream 的误报.SONARJAVA-1478

So yes S2095 is a false positive for IntStream. That will be hopefully fixed by SONARJAVA-1478

这篇关于IntStream 何时真正关闭?SonarQube S2095 是 IntStream 的误报吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:IntStream 何时真正关闭?SonarQube S2095 是 IntStream 的误报吗?