How does a “finalizer guardian” work in java?

断了今生、忘了曾经 提交于 2019-12-18 12:59:10

问题


How does a "finalizer guardian" [Effective Java , page 30] work ?

Have you used them? Did it solve any specific problem ?


回答1:


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");
    }

}


来源:https://stackoverflow.com/questions/6872857/how-does-a-finalizer-guardian-work-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!