问题描述
Stream 的 javadoc 声明:
The javadoc for Stream states:
Streams 有一个 BaseStream.close() 方法并实现了 AutoCloseable,但几乎所有的流实例实际上不需要在使用后关闭.通常,只有源是 IO 通道的流(例如 Files.lines(Path, Charset) 返回的流)才需要关闭.大多数流由集合、数组或生成函数支持,不需要特殊的资源管理.(如果流确实需要关闭,则可以在 try-with-resources 语句中将其声明为资源.)
因此,在绝大多数情况下,您可以单行使用 Streams,例如 collection.stream().forEach(System.out::println);
但对于 Files.lines
和其他资源支持的流,必须使用 try-with-resources 语句,否则会泄漏资源.
Therefore, the vast majority of the time one can use Streams in a one-liner, like collection.stream().forEach(System.out::println);
but for Files.lines
and other resource-backed streams, one must use a try-with-resources statement or else leak resources.
这让我觉得很容易出错并且没有必要.由于 Streams 只能迭代一次,在我看来,Files.lines
的输出不应该在迭代后立即关闭,因此实现应该简单在任何终端操作结束时隐式调用 close.我错了吗?
This strikes me as error-prone and unnecessary. As Streams can only be iterated once, it seems to me that there is no a situation where the output of Files.lines
should not be closed as soon as it has been iterated, and therefore the implementation should simply call close implicitly at the end of any terminal operation. Am I mistaken?
推荐答案
是的,这是一个深思熟虑的决定.我们考虑了两种选择.
Yes, this was a deliberate decision. We considered both alternatives.
这里的操作设计原则是谁获取资源就释放资源".当您读取到 EOF 时,文件不会自动关闭;我们希望文件被打开的人明确关闭.由 IO 资源支持的流是相同的.
The operating design principle here is "whoever acquires the resource should release the resource". Files don't auto-close when you read to EOF; we expect files to be closed explicitly by whoever opened them. Streams that are backed by IO resources are the same.
幸运的是,该语言为您提供了一种自动化机制:try-with-resources.因为 Stream 实现了 AutoCloseable,你可以这样做:
Fortunately, the language provides a mechanism for automating this for you: try-with-resources. Because Stream implements AutoCloseable, you can do:
try (Stream<String> s = Files.lines(...)) {
s.forEach(...);
}
自动关闭真的很方便,所以我可以把它写成单行"的论点很好,但主要是摇尾巴的狗.如果您打开了一个文件或其他资源,您也应该准备好关闭它.有效且一致的资源管理胜过我想在一行中写这个",我们选择不扭曲设计只是为了保持一行.
The argument that "it would be really convenient to auto-close so I could write it as a one-liner" is nice, but would mostly be the tail wagging the dog. If you opened a file or other resource, you should also be prepared to close it. Effective and consistent resource management trumps "I want to write this in one line", and we chose not to distort the design just to preserve the one-line-ness.
这篇关于为什么 Files.lines(和类似的 Streams)不会自动关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!