当Closeable对象被垃圾回收时,是否会调用Closeable接口的close()方法?在java 6.0中
我有一个静态变量,它是一个资源(数据库连接)。因为这是一个静态资源,所以没有正确的地方显式调用close()。
发布于 2011-11-30 14:19:43
简单的回答是:不会。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);
}
}
}问题是,它产生的问题比它的价值更多:例如,JVM不能保证它会调用这个方法。也就是说,您永远不应该使用它来处理资源;您在上面看到的是一个安全网,它使文件处理程序泄漏的破坏性更小。
还有另一个问题是,只要你的类是可见的,static field will not be garbage collected-that就是。所以你没有机会使用finalisation。
但是,您可以做的是使用Runtime.addShutdownHook()(http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread%29)—it将向您的应用程序添加另一层安全网,让您有机会在退出时优雅地关闭连接。假设您使用的是静态字段,那么连接的生命周期很可能与JVM的生命周期相同。
尽管如此,我还是建议您回顾一下这种方法。
发布于 2011-11-30 14:04:26
也许你可以使用finalization
发布于 2011-11-30 14:13:45
这取决于"Closeable“接口的实现,它希望如何处理垃圾收集。例如,FileInputStream实现Object#finalize()方法,以调用Closeable#close()方法。
https://stackoverflow.com/questions/8321767
复制相似问题