in the Spring Data JPA docs it says regarding streams:
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.
See: http://docs.spring.io/spring-data/jpa/docs/1.10.1.RELEASE/reference/html/#repositories.query-streaming
If I process a stream with forEach
, a count or another terminal operation, it should already be closed (and not be reused again) and I wouldn't have to wrap the stream in additional try-resources-block (given that my blocks don't throw any exception), or am I wrong here?
The Java APIs describe this topic as follows:
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.)
Also note the API for Files.lines(Path, Charset))
:
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.
Bottom line is: if the stream corresponds to a resource that, in normal scenarios need to be closed after use (like IO), use it in a try-with-resources statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With