Finalize()方法只被对象调用一次,而且,就算你执行了System.gc(),对象也不一定就马上执行Finalize方法。
public class FinalizeTest {
public static FinalizeTest SAVE_OK = null;
@Override
protected void finalize() throws Throwable {
super.finalize();
System.out.println("finalize method run");
FinalizeTest.SAVE_OK = this;
}
public static void main(String[] args) throws Exception{
SAVE_OK = new FinalizeTest(); //对象引用数为1
SAVE_OK = null; //对象引用指数为0
System.gc();
Thread.sleep(1000); //Finalizer 方法优先级很低,暂停1秒
if(SAVE_OK != null){
System.out.println("live");
}else{
System.out.println("dead");
}
SAVE_OK = null; //对象引用指数为0
System.gc();
Thread.sleep(1000); //Finalizer 方法优先级很低,暂停1秒
if(SAVE_OK != null){
System.out.println("live");
}else{
System.out.println("dead");
}
}
}
output:
finalize method run
live
dead