java - 我是否必须在 try-with-resources-block 中关闭已终止的流式查询结果?

标签 java java-8 spring-data-jpa java-stream

<分区>

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

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

如果我使用 forEach、计数或其他终端操作处理流,它应该已经关闭(并且不会再次重用)并且我不必在额外的尝试中包装流-resources-block(假设我的 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 语句中使用它。

关于java - 我是否必须在 try-with-resources-block 中关闭已终止的流式查询结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37659872/

相关文章:

JAVA - 在主方法中创建数组列表并在其他类中使用它而不重新创建它

java - 使用方法引用与 lambda 时,堆栈跟踪的可导航性是否较低?

Java8 : LocalDateTime or TimeStamp

java - 如何在Spring Boot中使用MySql数据库查询?

jpa - Spring Boot 2 - H2 数据库 - @SpringBootTest - org.h2.jdbc.JdbcSQLException : Table already exists 失败

spring-boot - 无法使用 Mockito 模拟 Spring-Data-JPA 存储库

java - java.lang.NullPointerException 导致接收广播 Intent 时出错

java - java和php之间的细微差别

java - 我在使用静态 main 方法和输入非静态值时遇到问题

multithreading - 在 supplyAsync 阻塞主线程后使用 thenAccept