It's well known that Javadoc says about Stream
interface:
Streams have a BaseStream.close() method and implement AutoCloseable, but nearly all stream instances do not actually need to be closed after use. Generally, only streams whose source is an IO channel (such as those returned by Files.lines(Path, Charset)) will require closing. Most streams are backed by collections, arrays, or generating functions, which require no special resource management. (If a stream does require closing, it can be declared as a resource in a try-with-resources statement.)
Ok, but at the same time there are methods like flatMapToInt
in this interface:
IntStream flatMapToInt(Function<? super T, ? extends IntStream> mapper);
for which Javadoc specification says:
Each mapped stream is closed after its contents have been placed into this stream.
So, I didn't get the idea: if IntStream
isn't designed to have IO channel in its source, why is it closed inside this method?
For example, ReferencePipeline
implementation does it in this way:
try (IntStream result = mapper.apply(u)) {
if (result != null)
result.sequential().forEach(downstreamAsInt);
}
More general question could be: should we care about closing streams like IntStream
(or its descendants) or not? If not, then why does flatMapTo*
care?
EDIT @Tunaki has provided me with a very interesting email link. But this all is about flatMap
, where, I agree, we should close the stream in general case. But my question is about special cases: flatMapToInt
, flatMapToLong
and so on, where I don't see any necessity of closing streams.
EDIT-2 @BrianGoetz is appealed here, because it is his cited email, therefore he is in the subject :)