“终结者监护人”如何?在java中工作? [英] How does a "finalizer guardian" work in java?
问题描述
finalizer guardian[Effective Java,page 30]如何工作?
你用过它们吗?它解决了任何特定的问题吗?
它解决了忘记调用 finalize
超类的方法。这种模式通过附加一个额外的实例并重写 finalize
给你的超类。这样,如果超类超出范围,则附加实例也将超出范围,这将触发 finalize
的执行,然后依次调用封闭类的 finalize
。
下面是一个简短的代码片段, p>
public class Parent {
public static void main(final String [] args)throws Exception {
doIt();
System.gc();
Thread.sleep(5000); // 5秒睡眠
}
@SuppressWarnings(unused)
private final object object guardian = new Object(){
@Override protected void finalize() {
doFinalize();
}
};
private void doFinalize(){
System.out.println(Final class of Parent);
public static void doIt(){
Child c = new Child();
System.out.println(c);
}
}
class Child extends Parent {
//注意,Child类不会调用super.finalize(),但是
//父类持有的资源仍然会被清除,这要归功于监护人模式
@Override protected void finalize(){
System.out.println(Finalize of class儿童);
}
}
How does a "finalizer guardian" [Effective Java , page 30] work ?
Have you used them? Did it solve any specific problem ?
It solves the problem of the sub-class forgetting to call the finalize
method of the super-class. This pattern works by attaching an extra instance with overridden finalize
to your super-class. This way, if the super-class goes out of scope, the attached instance would also go out of scope, which would trigger the execution of its finalize
, which would in turn call the finalize
of the enclosing class.
Here is a short snippet that showcases the guardian pattern in action:
public class Parent {
public static void main(final String[] args) throws Exception {
doIt();
System.gc();
Thread.sleep(5000); // 5 sec sleep
}
@SuppressWarnings("unused")
private final Object guardian = new Object() {
@Override protected void finalize() {
doFinalize();
}
};
private void doFinalize() {
System.out.println("Finalize of class Parent");
}
public static void doIt() {
Child c = new Child();
System.out.println(c);
}
}
class Child extends Parent {
// Note, Child class does not call super.finalize() but the resources held by the
// parent class will still get cleaned up, thanks to the guardian pattern
@Override protected void finalize() {
System.out.println("Finalize of class Child");
}
}
这篇关于“终结者监护人”如何?在java中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!