zoukankan      html  css  js  c++  java
  • Effective Java 英文 第二版 读书笔记 Item 7:Avoid finalizers

    Finalizers are unpredictable,often dangerous,and generally unnecessary.

    Their use can cause erratic behavior,poor performance,and portability problems.

    Finalizers have a few valid uses,which we’ll cover later in this item,but as a rule of thumb,you should avoid finalizers.

    C++ programmers are cautioned not to think of finalizers as Java’s analog of C++ destructors.In C++,destructors are the normal way to reclaim the resources associated with an object,a necessary counterpart to constructors.In java,the garbage collector reclaims the storage associated with an object when it becomes unreachable,requiring no special effort on the part of the programmer.C++ destructors are also used to reclaim other nonmemory resources.In java,the try-finally block is generally used for this purpose.

    //try-finally block guarantees execution of termination method
    Foo foo=new Foo();
    Try{
        //Do what must be done wit foo
    }finally{
    //Provide an explicit termination method.
        foo.terminate(); //Explicit termination method
    }

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

    But the finalizer should log a warning if it finds that the resource has not been terminated.

    //Finalizer Guardian idiom
    Public class Foo{
        //Sole purpose of this object is to finalize outer Foo object 
        Private final Object finalizerGuardian=new Object(){
            Protected ovid finalize thros Throwable{
        ……// Finalize outer Foo object
    }
    };
        //remainder omitted
    }
  • 相关阅读:
    Lampda或Linq中的SqlFunctions.StringConvert()
    Quartz.NET配置
    C#中TransactionScope的使用方法和原理
    .NET中使用Redis(二)
    曲苑杂坛--修改数据库名和文件组名
    曲苑杂坛--修改数据库服务器名称
    系统数据库--修改tempdb的位置
    系统数据库--恢复Master数据库
    TSQL--游标Dem
    TSQL--约束基础和Demo
  • 原文地址:https://www.cnblogs.com/linkarl/p/4820388.html
Copyright © 2011-2022 走看看