NOTE

  1. Never do anything time-critical in a finalizer.
  2. Never depend on a finalizer to update critical persistent state.
  3. There is a severe performance penalty for using.
  4. "Finalizer chaining" is not performed automatically. The subclass finalizer must invoke the superclass finalizer manually.
    1. Manual finalizer chaining

    @Override

    protected void finalize() throws Throwable {

    try {

    ... // Finalize subclass state

    } finally {

    super.finalize();

    }

    }

    b. Finalizer Guardian idiom

    // Finalizer Guardian idiom. This will prevent the subclass forgets to invoke super class's finalize method.

    public class Foo {

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

    private final Object finalizerGuardian = new Object() {

    @Override protected void finalize() throws Throwable {

    ... // Finalize outer Foo object

    }

    };

    ... // Remainder omitted

    }

What to do

  1. Provide an explicit termination method

the explicit termination method must record in a private field that the object is no longer valid, and other methods must check this field and throw an IllegalStateException if they are called after the object has been terminated.

  1. Explicit termination methods are typically used in combination with the try-finally construct to ensure termination.

    // try-finally block guarantees execution of termination method

    Foo foo = new Foo(...);

    try {

    // Do what must be done with foo

    ...

    } finally {

    foo.terminate(); // Explicit termination method

    }

Usage of finallizer

  1. Safety net: ensure the resources being released even if the explicitly termination method is not executed correctly.

    Note: the finalizer should log a warning if it finds that the resource has not been terminated

  2. Concerns objects with native peers. A native peer is a native object to which a normal object delegates via native methods. Because a native peer is not a normal object, the garbage collector doesn't know about it and can't reclaim it when its Java peer is reclaimed. A finalizer is an appropriate vehicle for performing this task, assuming the native peer holds no critical resources.

Summary

In summary, don't use finalizers except as a safety net or to terminate noncritical native resources. In those rare instances where you do use a finalizer, remember to invoke super.finalize. If you use a finalizer as a safety net, remember to log the invalid usage from the finalizer. Lastly, if you need toassociate a finalizer with a public, nonfinal class, consider using a finalizer guardian, so finalization can take place even if a subclass finalizer fails to invoke super.finalize.

Effective Java 07 Avoid finallizers的更多相关文章

  1. Effective Java 67 Avoid excessive synchronization

    Principle To avoid liveness and safety failures, never cede control to the client within a synchroni ...

  2. Effective Java 50 Avoid strings where other types are more appropriate

    Principle Strings are poor substitutes for other value types. Such as int, float or BigInteger. Stri ...

  3. Effective Java 73 Avoid thread groups

    Thread groups were originally envisioned as a mechanism for isolating applets for security purposes. ...

  4. Effective Java 05 Avoid creating unnecessary objects

    String s = new String("stringette"); // Don't do this. This will create an object each tim ...

  5. Effective Java 48 Avoid float and double if exact answers are required

    Reason The float and double types are particularly ill-suited for monetary calculations because it i ...

  6. Effective Java 59 Avoid unnecessary use of checked exceptions

    The burden is justified if the exceptional condition cannot be prevented by proper use of the API an ...

  7. Effective Java Index

    Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...

  8. Effective Java 创建和销毁对象

    <Effective Java>阅读笔记,用适合自己理解的方式提炼该书内容.<Effective Java>是一本很实用的书,阅读方法应该是快速的领会,总结,然后应用.而非,一 ...

  9. Effective Java 第三版——22. 接口仅用来定义类型

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

随机推荐

  1. js-变量

    一.变量的类型  Javascript和Java.C这些语言不同,它是一种无类型.弱检测的语言.它对变量的定义并不需要声明变量类型,我们只要通过赋值的形式,可以将各种类型的数据赋值给同一个变量.例如: ...

  2. IE11之F12 Developer Tools--控制台工具(Console)

    前面我们介绍了IE11的Developer Tools中的第一个工具--DOM Explorer,这篇文章介绍第二个工具--控制台(Console),使用控制台工具查看错误和其他信息.发送调试输出.检 ...

  3. 使用MyBatis查询int类型字段,返回NULL值时报异常的解决方法

    当配置mybatis返回int类型时 select id="getUserIdByName" parameterType="string" resultType ...

  4. SQLServer根据不同前缀生成多套流水号

    --种子表 --@prefix 前缀 --@seed 种子值 create table RefNoSeed( prefix ) unique, seed int ) go --测试表 --@inser ...

  5. windbg sos加载相关

    使用windbg 加载sos.dll时,经常碰到报The call to LoadLibrary(C:\Windows\Microsoft.NET\Framework\v4.0.30319\sos.d ...

  6. Python打包-py2exe使用

    Py2exe 64位下载地址:http://download.csdn.net/detail/henujyj/8532827 Py2exe 32位下载地址:https://sourceforge.ne ...

  7. 与众不同 windows phone (46) - 8.0 通信: Socket, 其它

    [源码下载] 与众不同 windows phone (46) - 8.0 通信: Socket, 其它 作者:webabcd 介绍与众不同 windows phone 8.0 之 通信 Socket ...

  8. Visual Studio中附加调试器的方法

    添加一个空的C++项目,项目属性配置如图. 命令里写要调试的程序的完整路径. 工作目录写所在目录的路径.

  9. Python关键字参数

    关键字参数允许你传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict.请看示例: #!/usr/bin/env python # -*- coding: utf-8 -*- ...

  10. javascript Array 方法学习

    原生对象Array学习 Array.from()   从类似数组的对象或可迭代的对象返回一个数组 参数列表 arraylike  类似数组的对象或者可以迭代的对象 mapfn(可选)   对对象遍历映 ...