简体   繁体   English

为什么Java 8 Stream类AutoCloseable?

[英]Why is Java 8 Stream class AutoCloseable?

In Java 8, the Stream class implements AutoCloseable. 在Java 8中,Stream类实现了AutoCloseable。 This means that a stream instance should be closed explicitly. 这意味着应该显式关闭流实例。

I understand why file handlers and DB connections are closeable. 我理解为什么文件处理程序和数据库连接是可关闭的。 But why streams? 但为什么流?

I think the current documentation/javadoc of Stream is pretty clear: 我认为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. Streams有一个BaseStream.close()方法并实现AutoCloseable,但几乎所有的流实例实际上都不需要在使用后关闭。 Generally, only streams whose source is an IO channel (such as those returned by Files.lines(Path, Charset)) will require closing. 通常,只有源为IO通道的流(例如Files.lines(Path,Charset)返回的流)才需要关闭。 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.) (如果流确实需要关闭,则可以在try-with-resources语句中将其声明为资源。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM