Why is Java 8 Stream class AutoCloseable?

2019-02-16 09:53发布

问题:

In Java 8, the Stream class implements AutoCloseable. This means that a stream instance should be closed explicitly.

I understand why file handlers and DB connections are closeable. But why streams?

回答1:

I think the current documentation/javadoc of Stream is pretty clear:

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