`
leonzhx
  • 浏览: 796696 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Item 7: Avoid finalizers

阅读更多

1.  Finalizers are unpredictable, often dangerous, and generally unnecessary. As a rule of thumb, you should avoid finalizers.

 

2.  One shortcoming of finalizers is that there is no guarantee they’ll be executed promptly. This means that you should never do anything time-critical in a finalizer.

 

3.  It is a grave error to depend on a finalizer to close files, because open file descriptors are a limited resource.

 

4.  The promptness with which finalizers are executed is primarily a function of the garbage collection algorithm, which varies widely from JVM implementation to JVM implementation.

 

5.  Providing a finalizer for a class can, under rare conditions, arbitrarily delay reclamation of its instances. Because the finalizer thread runs at a lower priority than another application thread, so objects may not get finalized at the rate they become eligible for finalization.

 

6.  Java language specification provides no guarantee that finalizers will get executed at all. A program may terminate without executing finalizers on some objects that are no longer reachable. As a consequence, you should never depend on a finalizer to update critical persistent state.

 

7.  System.gc and System.runFinalization may increase the odds of finalizers getting executed, but they don’t guarantee it.

 

8.  If an uncaught exception is thrown during finalization, the exception is ignored, and finalization of that object terminates. Uncaught exceptions can leave objects in a corrupt state. If another thread attempts to use such a corrupted object, arbitrary nondeterministic behavior may result.

 

9.  There is a severe performance penalty for using finalizers.

 

10.  Provide an explicit termination method which should do whatever is required to free the critical resource and require clients of the class to invoke this method on each instance when it is no longer needed. The instance must keep track of whether it has been terminated: 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.( Such as close methods on InputStream, OutputStream and java.sql.Connection. )

 

11.  The cancel method on java.util.Timer, which performs the necessary state change to cause the thread associated with a Timer instance to terminate itself gently.

 

12.  Image.flush deallocates all the resources associated with an Image instance but leaves it in a state where it can still be used, reallocating the resources if necessary.

 

13.  Explicit termination methods are typically used in combination with the try-finally construct to ensure termination. Invoking the explicit termination method inside the finally clause ensures that it will get executed even if an exception is thrown while the object is being used.

 

14.  One legitimate use for finalizer is to act as a “safety net” in case the owner of an object forgets to call its explicit termination method. But the finalizer should log a warning if it finds that the resource has not been terminated. Think long and hard about whether the extra protection is worth the extra cost. FileInputStream, FileOutputStream, Timer, and Connection have finalizers that serve as safety nets in case their termination methods aren’t called but they don’t log warnings.

Commented by Sean: Timer doesn't do that in JDK 7.

 

15.  A second legitimate use of finalizers concerns objects with native peers. A native peer is a native object to which a normal object delegates via native methods. A finalizer is an appropriate vehicle for performing this task, assuming the native peer holds no critical resources.

 

16.  The subclass finalizer must invoke the superclass finalizer manually. You should finalize the subclass in a try block and invoke the superclass finalizer in the corresponding finally block. This ensures that the superclass finalizer gets executed even if the subclass finalization throws an exception.

 

17.  Instead of putting the finalizer on the class requiring finalization, put the finalizer on an anonymous class whose sole purpose is to finalize its enclosing instance. It’s called finalizer guardian:

// Finalizer Guardian idiom
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
}

so it doesn’t matter whether a subclass finalizer calls super.finalize or not.

分享到:
评论

相关推荐

    Effective Java 3rd edition(Effective Java第三版英文原版)附第二版

    Item 7: Eliminate obsolete object references Item 8: Avoid finalizers and cleaners Item 9: Prefer try-with-resources to try-finally 3 Methods Common to All Objects Item 10: Obey the general contract ...

    effective java 读书笔记

    - Item7:Java中的finalizers用于清理对象资源,但不应依赖其执行,因为它们可能不会被调用,而且会影响垃圾收集性能。 4. **通用方法设计** - Item8:equals方法应与`==`操作符一致,同时对所有字段进行比较。...

    Effictive Java

    ##### Item7:在覆盖`equals`方法时遵循一般契约 - **目的**:确保`equals`方法的一致性和正确性。 - **实现方式**: - 在覆盖`equals`方法时,需确保遵循其一般契约,包括自反性、对称性、传递性以及一致性。 - ...

    finalizers:愚蠢的终结者

    愚蠢的终结者建造go build 跑# List all objects blocked by a finalizer./finalizers# List all objects with finalizers./finalizers --all例子./finalizersNAMESPACE NAME APIVERSION KIND FINALIZERSp-nf5gh ...

    Google Java 编程规范(中文版).pdf

    #### 7. 注释 **7.1 Javadoc** - **格式**: Javadoc应遵循特定的格式,包括必要的标记、段落等。 - **规范**: Javadoc应该包含在类、方法等公共API元素的上方,以提供关于其用途、参数、返回值等信息。 #### 8. ...

    Java编码规范1

    10. **不要使用Finalizers(终结)**:Finalizers在对象生命周期结束时执行,但其执行时间不确定,可能导致资源泄露。通常,应使用`try-finally`或`try-with-resources`来确保资源的释放。 11. **完全限定imports**...

    flexipatch-finalizer:自定义预处理器,用于从flexipatch版本中删除未选择的补丁,从而保留最终的补丁版本

    大多数软件都具有基本功能,可以通过应用代码补丁进行扩展。 这通常涉及代表最终用户进行大量修补,尤其是在应用多个修补程序时。 flexipatch构建对补丁的处理方式有所不同,在预处理过程中,预处理器指令用于确定...

    gradle-7.5.1-all.zip 快速下载

    3、当上游任务失败时,finalizers 的 finalizers 不再执行 4、CheckStyle 失败,因为它没有配置 javaLauncher 5、更新升级指南以警告 Checkstyle 工作目录中的更改 6、将设置为具有 ValueSourceParameters.None ...

    C++_CLI标准.pdf

    - **Destructors and Finalizers**: Section 8.8.8 discusses destructors and finalizers in ref classes. - **Static Constructors**: Section 8.8.9 covers static constructors in ref classes. - **...

    Troubleshooting Memory Problems-Poonam Parhar.pdf

    7. Application Failure with OutOfMemoryError:OutOfMemoryError是Java应用程序中的一个常见错误,它可以导致应用程序崩溃。 8. Unexpected Memory Growth:内存使用率的不稳定增长可以导致应用程序性能下降和崩溃...

    android编程规范

    7. **行长度**: 每行代码不超过100列,以保持代码的可读性。 8. **字段命名**: 非公共、非静态字段以`m`开头,静态字段以`s`开头。 9. **花括号(Braces)**: 开始花括号与语句在同一行,不另起一行。 10. **注解...

    A-JVM-Does-What-Cliff Click.pdf

    7. 统一线程和内存模型(Uniform Threading & Memory Model):JVM 的统一线程和内存模型能够简化多线程编程,提高系统的可靠性和安全性。 8. 锁、volatile、wait、notify(Locks, volatile, wait, notify):JVM 的...

    JProfiler Helper

    Finalizers can significantly affect garbage collection and memory usage. This section discusses: - Identifying finalizers that may cause performance issues. - Configuring JProfiler to remove ...

    c#汇总,包括asp.net xml c#基础知识

    类包含属性(Fields)、方法(Methods)、构造器(Constructors)和析构函数(Finalizers)等成员。 5. 继承与多态:C#支持单一继承,一个类可以继承自另一个类,从而获取其特性。多态是通过抽象类(Abstract Class...

    愚蠢的终结者-Golang开发

    愚蠢的终结者Build go build Run#列出被终结者阻止的所有对象./finalizers#列出所有带有终结器的对象./finalizers --all Ex愚蠢的终结者Build go build Run#列出被终结器阻止的所有对象./finalizers#列出所有...

    商业源码-编程源码-Csharp高级编程第四版代码.zip

    7. LINQ(Language Integrated Query):学习如何使用LINQ进行数据查询,包括数据库查询和XML操作。 8. 异步编程:使用async和await进行异步操作,如网络请求、文件I/O等。 9. 自定义属性和元数据:理解属性的概念,...

    C#语言参考(DOC)

    7. 接口(Interfaces):接口定义了一组方法签名,类可以实现接口来保证遵循特定的约定。 8. 委托(Delegates):委托是C#中的一种类型,可以引用方法。它们在事件处理和回调机制中扮演重要角色。 9. 枚举(Enums...

Global site tag (gtag.js) - Google Analytics