[英]How does a “finalizer guardian” work in java?
How does a "finalizer guardian" [Effective Java , page 30] work ? “ finalizer监护人” [Effective Java,第30页]如何工作?
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. 解决了子类忘记调用超类的
finalize
方法的问题。 This pattern works by attaching an extra instance with overridden finalize
to your super-class. 这种模式通过将一个带有重写
finalize
的额外实例附加到您的超类来工作。 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. 这样,如果超类超出范围,则所附加的实例也将超出范围,这将触发其
finalize
的执行,而该finalize
进而将调用封闭类的finalize
。
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");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.