垃圾收集可以关闭吗?

raj*_*raj 6 java garbage-collection

当对象被垃圾回收时,是否会调用接口的close()方法?[在java 6.0中]CloseableCloseable

我有一个静态变量,它是一个资源(数据库连接).由于这是一个静态资源,因此没有正确的位置来close()显式调用.

alf*_*alf 8

快速回答:没有.GC根本不关心Closeable.

Java确实有protected void finalize() throws Throwable { }可以覆盖的方法 - 它将在GC上调用.它有点作用,例如FileInputStream:

/**
 * Ensures that the <code>close</code> method of this file input stream is
 * called when there are no more references to it.
 *
 * @exception  IOException  if an I/O error occurs.
 * @see        java.io.FileInputStream#close()
 */
protected void finalize() throws IOException {
    if ((fd != null) &&  (fd != FileDescriptor.in)) {

        /*
         * Finalizer should not release the FileDescriptor if another
         * stream is still using it. If the user directly invokes
         * close() then the FileDescriptor is also released.
         */
        runningFinalize.set(Boolean.TRUE);
        try {
            close();
        } finally {
            runningFinalize.set(Boolean.FALSE);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是,它产生的问题多于它的价值:例如,JVM并不能保证它会调用这个方法.也就是说,你永远不应该用它来进行资源处理; 你在上面看到的是一个安全网,使文件处理程序泄漏损害较小.

还有一个问题是,静态字段不会被垃圾收集 - 也就是说,只要你的类是可见的.所以你没有机会使用finalization.

但是,您可以使用Runtime.addShutdownHook()-it为您的应用程序添加另一层安全网,让您有机会在退出时优雅地关闭连接.鉴于您正在使用静态字段,无论如何,您的连接的生命周期可能与JVM的相同.

不过,我建议您重新审视这种方法.