java - java.sql.Connection 对象在垃圾收集时会自动关闭吗?

标签 java mysql sql garbage-collection

我遵循在最后一个 block 中放置一个 close() 的做法:

void foo() {
    Connection conn;
    try {
        conn = getConnection();
        // ..
    } final {
        try {
            conn.close()
        } catch(Exception e) {
        }
    }
}

是否真的有必要在连接上调用 close(),或者垃圾收集器会自动执行此操作?

我可以接受垃圾收集会导致的额外延迟,我只是不希望连接永远保持打开状态。

最佳答案

is it really necessary to call Close() on the connection

是的。

or the garbage collector will do that automatically?

未指定。也许某些实现会做到这一点。你不能依赖它。

I am OK with the extra delay that GC will induce.

GC 可能永远不会发生。你真的接受无穷大吗?

I just dont want the connections to remain open forever.

您不希望它们保持打开状态的时间超过必要时间。它们是一种稀缺资源。不要浪费它们。 "It is recommended that programmers explicitly close all connections (with the method Connection.close) and statements (with the method Statement.close) as soon as they are no longer needed, thereby freeing DBMS resources as early as possible."

关于java - java.sql.Connection 对象在垃圾收集时会自动关闭吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14843432/

相关文章:

java - 使用命令提示符运行 Java 程序时遇到问题

sql - 需要可移植的 SQL upsert(插入+更新)解决方案

mysql - Bugzilla 中分离客户端的基本权限

sql - 在 SQL Server 中替换

java - 不同风格的程序流程?

java - 如何修复 Hibernate LazyInitializationException : failed to lazily initialize a collection of roles, 无法初始化代理 - 无 session

java - 等待特定文本显示在下拉菜单中 - selenium

php - 使用 MySQL 基于时隙检索结果

sql - SQL Server 中的 For 循环和 if else 语句

MySQL重命名列