gpt4 book ai didi

Java 隐式 try-with-resources

转载 作者:太空狗 更新时间:2023-10-29 22:50:12 25 4
gpt4 key购买 nike

我想知道以下代码是否正确使用了 try-with-resources。

try (ResultSet rs = new QueryBuilder(connection, tableName(), getPaths(), searchQuery()).add(constraint).build().executeQuery()) {
while (rs.next()) {
beans.add(createBean(rs));
}
}

参数不重要,重要的是:

  • new QueryBuilder().build(); 返回一个 PreparedStatement

我完全理解 rs 将被关闭,但是 PreparedStatement 是否也会被关闭,如果是,是什么原因?因为 ResultSet 关闭还是因为 try-with-resources?

最佳答案

PreparedStatement#close()将自动关闭任何关联的结果集,但反之则不然,因为语句在其结果集关闭后可重用。

查看ResultSet#close()的javadoc :

Note: A ResultSet object is automatically closed by the Statement object that generated it when that Statement object is closed

然后 Statement#close() :

Note: When a Statement object is closed, its current ResultSet object, if one exists, is also closed.

这种用法在我看来很糟糕:

ResultSet rs=conn.createStatement().executeQuery();

如果执行的次数足够多,它将泄漏所有可用的游标,因为游标与 Statement 相关联,而不是与 ResultSet 相关联。

因此用 try-with-resources statement 关闭底层 PreparedStatement ,只需在 try 语句中声明它:

A try-with-resources statement is parameterized with variables (known as resources) that are initialized before execution of the try block and closed automatically.

this answer from assylias , 在 try 语句中声明 PreparedStatementResultSet

因为您不是在寻找内存泄漏,而是在寻找资源泄漏PreparedStatement 的内存最终将被收集并释放内存,因为在按照初始化方式执行您的方法后不再引用它,但是,资源由 Statement 保留 没有关闭。

关于Java 隐式 try-with-resources,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17788132/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com