Do I need to close completed streaming query results in a try-with-resources block?

the Spring Data JPA document talks about threads:

A thread potentially wraps underlying data stores with specific resources and therefore should be closed after use. You can manually close the Stream using the close () method or using the try-with-resources block of Java 7.

See: http://docs.spring.io/spring-data/jpa/docs/1.10.1.RELEASE/reference/html/#repositories.query-streaming

If I process a stream using forEach , an account or other terminal operation, it should already be closed (and will not be reused), and I would not have to wrap the stream in an additional try-resources-block (given that my blocks are not cause any exceptions), or am I wrong here?

+5
source share
1 answer

The Java APIs describe this question as follows:

Streams have a BaseStream.close() method and implement AutoCloseable , but almost all stream instances do not actually need to be closed after use. As a rule, only streams whose source is an I / O channel (for example, those returned by Files.lines(Path, Charset)) ) need to be closed. Most threads are supported by collections, arrays, or generation functions that do not require special resource management. (If a thread requires closure, it can be declared as a resource in the try-with-resources statement.)

Also pay attention to the API for Files.lines(Path, Charset)) :

The returned stream encapsulates a Reader. If timely removal of file system resources is required, the try-with-resources construct should be used to ensure that the stream close method is called after stream operations have completed.

Bottom line: if a stream corresponds to a resource that should be closed in normal scripts after use (for example, IO), use it in the try-with-resources statement.

+10
source

All Articles