Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is an IntStream actually closed? Is SonarQube S2095 a false positive for IntStream?

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?

like image 488
Bob Cross Avatar asked Jan 13 '16 14:01

Bob Cross


1 Answers

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

like image 153
Andremoniy Avatar answered Nov 02 '22 23:11

Andremoniy