阅读时间: 1分钟
名字跟final, finally 关键字很相似,但本质就有很大的分别。
finalize 只是Method,属于java.lang.Object类别。
finalize() method 一般会被叫做终结者。
终结者会被触发当JVM 计算出要执行garbage collection的时候. 而终结者会执行任何操作。
finalize() method 的主要作用是把物件的资源在被删除(garbage collection)之前释放出来或者进行结尾的动作。public class Finalizable { private BufferedReader reader; public Finalizable() { InputStream input = this.getClass() .getClassLoader() .getResourceAsStream("file.txt"); this.reader = new BufferedReader(new InputStreamReader(input)); } public String readFirstLine() throws IOException { String firstLine = reader.readLine(); return firstLine; } // other class members}
大家会留意到物件reader是仍然没有close,所以可以透过finalize()来执行close这个动作。
@Overridepublic void finalize() { try { reader.close(); System.out.println("Closed BufferedReader in the finalizer"); } catch (IOException e) { // ... }}
运用了finalize() {就可以完全保证reader这个资源能在整个程式进入garbage collection之前释放出来。