finalize()的一个用途:用作判断一个object(对象)的死亡条件,尤其是一些使用共享资源(例如:文件、数据库连接)的对象。例如:1个对象代表1个打开的文件,那么在对象被回收时,应该保证打开的文件被关闭。例如:java调用的c语言调用中分配的内存是否释放。
因此可以在finalize()中对使用的资源的释放情况进行判断,发现资源和内存泄漏错误。虽然finalize()不是每次都被JVM调到,但是还是很有帮助。
//: c04:DeathCondition.java
// Using finalize() to detect an object that
// hasn't been properly cleaned up.
class Book {
boolean checkedOut = false;
Book(boolean checkOut) {
checkedOut = checkOut;
}
void checkIn() {
checkedOut = false;
}
public void finalize() {
if(checkedOut)
System.out.println("Error: checked out");
}
}
public class DeathCondition {
public static void main(String[] args) {
Book novel = new Book(true);
// Proper cleanup:
novel.checkIn();
// Drop the reference, forget to clean up:
new Book(true);
// Force garbage collection & finalization:
System.gc();
}
} ///:~