幻影参考对象 [英] Phantom Referenced Objects
问题描述
Phantom References用于验尸操作。
Java规范规定,在清除幻像引用本身之前,不会释放幻像引用对象。
Phantom References serve for post-mortem operations. The Java specification states that a phantom referenced object will not be deallocated until the phantom-reference itself is cleaned.
我的问题是:这个功能(对象未解除分配)的目的是什么?
My question is: What purpose does this feature (object not deallocated) serve?
(我想出的唯一想法是允许本机代码进行事后清理对象,但它并不太令人信服。)
(The only idea i came up with, is to allow native code to do post-mortem cleanup on the object, but it isn't much convincing).
推荐答案
我能想到的唯一好的用例,那就是防止重新分配,是某种JNI实现的异步数据源写入引用对象的一种方式,必须告诉它要停下来 - 停止写入对象 - 在内存被回收之前。如果允许先前的释放,一个简单的忘记处置()错误可能导致内存损坏。
The only good use-case I can think of, that would prevent deallocation, is one where some kind of JNI-implemented asynchronous data source is writing into the referenced object, and must be told to stand down - to stop writing into the object - before the memory is recycled. If prior deallocation were allowed, a simple forgot-to-dispose() bug could result in memory corruption.
这是过去使用finalize()的情况之一,可能会引发一些怪癖。
This is one of the cases where finalize() would have been used in the past, and probably drove some of its quirks.
这篇关于幻影参考对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!