gpt4 book ai didi

java - 重用 PreparedStatement 时可能会发生资源泄漏?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:09:45 29 4
gpt4 key购买 nike

假设您有以下代码:

    Connection connection = null;
PreparedStatement ps = null;

try {
Connection = connectionFactory.getConnection();

ps = statement.prepareStamement(someQuery);
// execute and read and stuff

// now you want to use the ps again, since you don't want ps1, ps2, ps3, etc.
ps = statement.prepareStatement(someOtherQuery); // DOES THIS FORM A POTENTIAL LEAK?
} catch (a lot of exceptions) {
// process exceptions
} finally {

// close the resources (using util class with null-checks and everything)
SomeUtilClass.close(ps);
SomeUtilClass.close(connection);
}

重用 ps 变量是否存在潜在泄漏?

如果是这样,我不愿意声明多个这样的准备好的语句(ps1、ps2、ps3 等)。我应该如何重构它?

有什么想法吗?

编辑

收到多个答复,表明这无关紧要。我想指出的是,我遇到了打开的游标,它保持打开的时间有点太长了,我想知道这种模式是否与它有关。

我的想法是:

第一个语句被取消引用和 GC,那么在这个例子中第一个 PreparedStatement 是如何关闭的(数据库方面)?

最佳答案

这不一定会造成经典的“永久”意义上的泄漏。垃圾收集器最终会找到准备好的语句的第一个实例,并调用它的终结器。

但是,让垃圾收集器处理释放潜在的关键资源(例如 DB 句柄)并不是一个好的做法:您应该在重用准备好的语句变量之前调用 close 方法,否则完全重用变量。

try {
Connection = connectionFactory.getConnection();

ps = statement.prepareStamement(someQuery);
// execute and read and stuff

// now you want to use the ps again, since you don't want ps1, ps2, ps3, etc.
// v v v v v v v v v v v
SomeUtilClass.close(ps);
// ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
ps = statement.prepareStatement(someOtherQuery); // DOES THIS FORM A POTENTIAL LEAK?
} catch (a lot of exceptions) {
// process exceptions
} finally {

// close the resources (using util class with null-checks and everything)
SomeUtilClass.close(ps);
SomeUtilClass.close(connection);
}

关于java - 重用 PreparedStatement 时可能会发生资源泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22096398/

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