finalize()与PhantomReference学习笔记

众所周知,Java语言提供了自动垃圾回收机制,使得程序员不用考虑自己释放不再使用的内存。既然回收内存的活都让Java自己干了,程序员在这方面能干的事情就不多了。尽管如此,Java也提供了一些让程序员对自动内存回收施加影响的方式。finalize()和PhantomReference就是其中两种,它们都能在自动内存回收的特定时刻运行程序员提供的代码,通常这些代码用来回收一些自动回收机制无法回收的资源。

1. Object.finalize()

finalize()出现的较早,由于有以下的缺点,已经在Java 9中被弃用。

The finalization mechanism is inherently problematic. Finalization can lead to performance issues, deadlocks, and hangs. Errors in finalizers can lead to resource leaks; there is no way to cancel finalization if it is no longer necessary; and no ordering is specified among calls to finalize methods of different objects. Furthermore, there are no guarantees regarding the timing of finalization. The finalize method might be called on a finalizable object only after an indefinite delay, if at all.

2. PhantomReference

PhantomReference能够让程序员提供一个ReferenceQueue,当相关的对象被自动垃圾回收线程finalized时,对应的PhantomReference对象就会被放入ReferenceQueue,以此来通知程序员做一些资源清理工作。

3. 推荐的方法

如果使用这两种方式来释放系统资源,它们都无法知道程序员提供的清理动作会在何时被执行。因此,推荐的做法是:

Classes whose instances hold non-heap resources should provide a method to enable explicit release of those resources, and they should also implement AutoCloseable if appropriate.

 

参考资料

1. https://docs.oracle.com/javase/9/docs/api/java/lang/Object.html#finalize--

2. Java PhantomReferences: A better choice than finalize()

posted @ 2019-02-14 01:32  爪哇国臣民  阅读(473)  评论(0编辑  收藏  举报