finalize-方法名。Java 技术允许使用 finalize() 方法在垃圾收集器将对象从内存中清除出去之前做必要的清理工作。这个方法是由垃圾收集器在确定这个对象没有被引用时对这个对象调用的。垃圾收集器只知道释放那些由new分配的内存,所以不知道如何释放对象的“特殊”内存。为解决这个问题,Java提供了一个名为finalize()的方法,它的工作原理应该是这样的:一旦垃圾收集器准备好释放对象占用的存储空间,它首先调用finalize(),而且只有在下一次垃圾收集过程中,才会真正回收对象的内存。所以如果使用finalize(),就可以在垃圾收集期间进行一些重要的清除或清扫工作(如关闭流等操作)。
package Initialization;
class Tank{
int howFull = 0;
Tank() { this(0);}
Tank(int fullness){
howFull = fullness;
}
void sayHowFull(){
if(howFull == 0)
System.out.println("Tank is empty!");
else
System.out.println("Tank filling status : " + howFull);
}
void empty(){
howFull = 0;
}
protected void finalize(){
if(howFull != 0){
System.out.println("Error: Tank not empty." + this.howFull);
}
//Normally,you'll also do this:
//Super.finalize(); //call the base-class version
}
}
public class TankTest {
public static void main(String[] args) {
Tank tank1 = new Tank();
Tank tank2 = new Tank(3);
Tank tank3 = new Tank(5);
tank2.empty();
//Drop the reference,forget to cleanup:
new Tank(6);
new Tank(7);
System.out.println("Check tanks:");
System.out.println("tank1:");
tank1.sayHowFull();
System.out.println("tank2:");
tank2.sayHowFull();
System.out.println("tank3");
tank3.sayHowFull();
System.out.println("first forced gc()");
System.gc();
System.out.println("try deprecated runFinalizerOnExit(true)");
System.runFinalizersOnExit(true);
System.out.println("last forced gc():");
System.gc();
}
}
|