(Item 6) Avoid finalizer

本文探讨了Java中终结(finalization)机制的使用限制及替代方案。解释了为什么不应依赖终结器进行关键操作,并提供了使用明确终止方法和尝试-最终块的建议。还介绍了终结器链的概念以及如何通过内部类实现终结守护程序。

(Item 6) Avoid finalizer

1) Java Language Specification provide no guarantee that finalizer will get executed.

2) Nothing time-critical should ever be done in finalizer (e.g. close file)

3) Don’t seduced by System.gc and System.runFinalization, they don’t guarantee the finalizer get executed

4) System.runFinalizationOnExit(or Runtime.runFinalizationOnExit) claim to guarantee finalization but those method are fatally flawed and have been deprecated

5) An uncaught exception will be ignored in finalize()

6) Provider a explicit method for termination and require client of class invoke it. (e.g. InputStream.close() is such a termination method)

7) Combine termination method with try-finally block

8)what are finalize() good for?

        a) Last safety net

        b) For “native peer”, (e.g. invoking C++ new() to create object, then you can call delete in finalizer)

9)finalizer chaining

// Manual finalizer chaining

protected void finalize() throws Throwable {

    try {

        // Finalize subclass state

        ...

    } finally {

        super.finalize();

or use finalizer guardian inner class, you need not call super.finalize()

// Finalizer Guardian idiom

public class Foo {

   // Sole purpose of this object is to finalize outer Foo object

   private final Object finalizerGuardian = new Object() {

      protected void finalize() throws Throwable {

         // Finalize outer Foo object

         ...

      }

   };

   ...  // Remainder omitted

}

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值