Effective Java 英文 第二版 读书笔记 Item 7:Avoid finalizers

Finalizers are unpredictable,often dangerous,and generally unnecessary,in java.

may cause poor ferformance,instability behavior,and portability(移植)  problems.

so avoid finalizers as as possible.

never do anything time-critical in a finalizer,

for example: 

A colleague debugged a long-running GUI application that was mysteriously dying with an OutOfMemoryError.

Analysis revealed that at the time of its death,the application had thousands of graphics objects on its finalizer queue just waiting to be finalized and reclaimed. 

Unfortunately,the finalizer thread was running at a lower priority than another application thread.

同事debug一个长时间运行的图形应用报错OutOfMemoryError(内存不足错误),

分析发现对象死亡的同时,这个应用仍然数千个图形对象在其finalizer队列等待被终结、回收,

不幸运的是,finalizer线程优先级低于应用其他线程

程序不能保证finalizers的执行,当显式调用时。

never depend on a finalizer to update critical persistent state

instead of writing a finalizer for a class whose objects encapsulate resources that require termination,

just provide an explicit termination method,

比如数据流和数据库连接的关闭

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

利用finally保证执行关闭

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

原文地址:https://www.cnblogs.com/linkarl/p/5527609.html