Blackrush
Blackrush

Reputation: 117

Why is not java.util.stream.Stream#close() called?

When collecting a java.util.stream.Stream, why is not its method void close() called ?

Upvotes: 6

Views: 1669

Answers (2)

duffymo
duffymo

Reputation: 309008

Do you mean garbage collecting?

This would imply that the garbage collector would have to know a lot about the objects it's cleaning up. I don't think that's a good idea for a GC implementation to worry about.

Cleaning up after scarce resources is your responsibility as a developer. This is what try/finally was born for.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201527

Per the Stream javadoc,

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.)

So, it sounds like you need to use a try-with-resources Statement.

Upvotes: 5

Related Questions