Why is Java 8 Stream class AutoCloseable?

a 夏天 提交于 2019-12-19 05:22:48

问题


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



来源:https://stackoverflow.com/questions/22125169/why-is-java-8-stream-class-autocloseable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!