Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to close terminated, streamed query results in a try-with-resources-block? [duplicate]

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?

like image 690
Michael Simons Avatar asked Jun 06 '16 14:06

Michael Simons


1 Answers

The Java APIs describe this topic as follows:

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

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's close 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.

like image 134
M A Avatar answered Nov 05 '22 19:11

M A