幻像引用的对象

时间:2020-03-05 18:58:08  来源:igfitidea点击:

幻影引用用于事后操作。
Java规范指出,幻影引用的对象在清理幻影引用本身之前不会被释放。

我的问题是:此功能(未释放的对象)起什么作用?

(我想出的唯一想法是,允许本机代码对对象进行事后清理,但这并不是很令人信服)。

解决方案

回答

编辑,因为我先误解了这个问题:

从这里引用http://www.memorymanagement.org/glossary/p.html:

The Java specification says that the
  phantom reference is not cleared when
  the reference object is enqueued, but
  actually, there's no way in the
  language to tell whether that has been
  done or not. In some implementations,
  JNI weak global references are weaker
  than phantom references, and provide a
  way to access phantom reachable
  objects.

但是我没有找到其他引用相同的内容。

回答

它可以允许我们拥有两个幻像缓存,它们在内存管理中非常有效。
简而言之,如果我们创建的大型对象昂贵但很少使用,则可以使用幻像缓存来引用它们,并确保它们不会占用更有价值的内存。如果使用常规引用,则必须手动确保该对象没有剩余的引用。我们可以对任何对象争论不休,但不必手动管理幻像缓存中的引用。只需小心检查它们是否已被收集。

我们也可以使用框架(即工厂),其中引用以幻像引用的形式给出。如果对象寿命短(即先使用后丢弃),这将很有用。如果我们有马虎的程序员认为垃圾回收很神奇,那么清除内存非常方便。

回答

我认为这个想法是让其他对象在原始对象之外进行额外的清理。例如,如果无法扩展原始对象以实现某些终结处理,则可以使用幻像引用。

更大的问题是,JVM不保证对象将最终完成,并且我通过扩展假设不保证幻象引用可以在完成后完成它们的工作。

回答

Phantom references can be used to perform pre-garbage collection actions such as freeing resources. Instead, people usually use the finalize() method for this which is not a good idea. Finalizers have a horrible impact on the performance of the garbage collector and can break data integrity of your application if you're not very careful since the "finalizer" is invoked in a random thread, at a random time.

In the constructor of a phantom reference, you specify a ReferenceQueue where the phantom references are enqueued once the referenced objects becomes "phantom reachable". Phantom reachable means unreachable other than through the phantom reference. The initially confusing thing is that although the phantom reference continues to hold the referenced object in a private field (unlike soft or weak references), its getReference() method always returns null. This is so that you cannot make the object strongly reachable again.

From time to time, you can poll the ReferenceQueue and check if there are any new PhantomReferences whose referenced objects have become phantom reachable. In order to be able to to anything useful, one can for example derive a class from java.lang.ref.PhantomReference that references resources that should be freed before garbage collection. The referenced object is only garbage collected once the phantom reference becomes unreachable itself.

http://www.javalobby.org/java/forums/m91822870.html#91822413