“终结器守护者”如何实现?在java中工作?

发布于 2024-11-26 23:46:02 字数 72 浏览 2 评论 0原文

“终结器守护者”[Effective Java,第 30 页] 如何工作?

你用过它们吗?它解决了任何具体问题吗?

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦初启 2024-12-03 23:46:02

解决了子类忘记调用超类的finalize方法的问题。此模式的工作原理是将一个带有重写的 finalize 的额外实例附加到您的超类。这样,如果超类超出范围,附加的实例也会超出范围,这将触发其 finalize 的执行,进而调用 finalize<封闭类的 /code> 。

下面是一个简短的片段,展示了守护者模式的实际应用:

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

}

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

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文