我是否必须在 try-with-resources-block 中关闭已终止的流式查询结果?
Do I have to close terminated, streamed query results in a try-with-resources-block?
在 Spring Data JPA 文档中它说关于流:
A Stream potentially wraps underlying data store specific resources and must therefore be closed after usage. You can either manually close the Stream using the close() method or by using a Java 7 try-with-resources block.
如果我使用 forEach
、计数或其他终端操作处理流,它应该已经关闭(并且不会再次重用)并且我不必将流包装在额外的 try- resources-block(假设我的块没有抛出任何异常),还是我错了?
Java APIs对本主题的描述如下:
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.)
另请注意 Files.lines(Path, Charset))
的 API:
The returned stream encapsulates a Reader.
If timely disposal of file system resources is required, the try-with-resources construct should be used to ensure that the stream's close
method is invoked after the stream operations are completed.
底线是:如果流对应的资源在正常情况下需要在使用后关闭(如 IO),请在 try-with-resources 语句中使用它。
在 Spring Data JPA 文档中它说关于流:
A Stream potentially wraps underlying data store specific resources and must therefore be closed after usage. You can either manually close the Stream using the close() method or by using a Java 7 try-with-resources block.
如果我使用 forEach
、计数或其他终端操作处理流,它应该已经关闭(并且不会再次重用)并且我不必将流包装在额外的 try- resources-block(假设我的块没有抛出任何异常),还是我错了?
Java APIs对本主题的描述如下:
Streams have a
BaseStream.close()
method and implementAutoCloseable
, 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 byFiles.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.)
另请注意 Files.lines(Path, Charset))
的 API:
The returned stream encapsulates a
Reader.
If timely disposal of file system resources is required, the try-with-resources construct should be used to ensure that the stream'sclose
method is invoked after the stream operations are completed.
底线是:如果流对应的资源在正常情况下需要在使用后关闭(如 IO),请在 try-with-resources 语句中使用它。