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

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

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

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

最佳答案



是的。



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



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



您不希望它们保持打开状态的时间超过必要时间。它们是稀缺资源。不要浪费它们。 "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/

10-10 04:11