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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值