java终结器guardian没有运行
程序退出时,我的finalizer guardian无法运行
他来了:
public class SomeClass implements SomeInterface {
... setup the PrintWriter os somewhere here
/** oh, i guess i wanted to try out finalizer guardians here. */
@SuppressWarnings("unused")
private final Object finalizerGuardian = new Object(){
protected void finalize(){
try {
//actually, i cannot know if it was closed or not.
System.out.println("connection wasn't closed - it needs to be!");
os.flush();
os.close();
} catch (Exception se){
System.out.println("some sort of exception occurred? Weird");
}
}
};
...
}
我做错了什么?我以为瓜迪亚人一定会跑?还是不是这样?当程序终止时,PrintWriter操作系统肯定不会刷新或关闭
# 1 楼答案
终结器线程是垃圾收集(GC)的一部分。虽然它确实是GC的一部分,但GC并不能保证它何时运行。Finalize方法将对象移动到finalizer objects队列,在该队列中,finalizer线程在运行时清除队列中存在的对象