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();
Note: I know there are other ways to do the counting that I show above. I'm doing it that way in order to illustrate my question.
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.
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?
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
:
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.
So yes S2095 is a false positive for IntStream. That will be hopefully fixed by SONARJAVA-1478
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With