java 中 phantomreference 的重要性

Importance of phantomreference in java

我想理解以下粗体字的表述。这是什么意思? (Link)

An object which overrides finalize() must now be determined to be garbage in at least two separate garbage collection cycles in order to be collected. When the first cycle determines that it is garbage, it becomes eligible for finalization. Because of the (slim, but unfortunately real) possibility that the object was "resurrected" during finalization, the garbage collector has to run again before the object can actually be removed. And because finalization might not have happened in a timely fashion, an arbitrary number of garbage collection cycles might have happened while the object was waiting for finalization. This can mean serious delays in actually cleaning up garbage objects, and is why you can get OutOfMemoryErrors even when most of the heap is garbage.

phantomreference解决了什么问题

With PhantomReference, this situation is impossible -- when a PhantomReference is enqueued, there is absolutely no way to get a pointer to the now-dead object (which is good, because it isn't in memory any longer). Because PhantomReference cannot be used to resurrect an object, the object can be instantly cleaned up during the first garbage collection cycle in which it is found to be phantomly reachable.

请帮助我理解问题和解决方案

谢谢

与流行的看法相反,finalize 方法不会在其关联的 object 为 garbage-collected 时触发,而是在其关联的 object 为 [=21= 时触发] 本来是 garbage-collected 但因为他们的 non-default finalize 方法的存在。 Objects 实际上不可能是 garbage-collected,直到系统可以 100% 确定不会 永远 存在对它们的引用,但是 运行ning 的行为finalize 方法会创建对相关 object 的强根引用,该引用至少会存在到该方法退出之前。如果在 finalize 的执行期间,对 object 的引用被存储在别处,该引用可能会无限期地继续存在。因此,没有 object 的 finalized 方法将被调用,也没有任何其他 object 这样的 object 拥有直接或间接的强引用,直到在 finalize 方法具有 运行 并且下一个 GC 周期确认不再存在对 object 的引用之后。

PhantomReference class 用于封装不同的范例:而不是让 object 保持活动状态以便系统可以通知它它已被放弃,这是它仍然存在的唯一原因以便它可以接收放弃通知,需要清理的 objects 应该创建助手 objects 来处理他们放弃的通知。如果助手 object 避免保留对任何他们不 "own" 的外部 object 的引用,它们的存在将不会干扰其 parent [=32] 的集合=],或 parent 直接或间接引用的其他 object。助手 object 通常不会持有足够的信息让他们 "do much",但这很好,因为他们不必做太多事情。相反,他们的设计应该专注于执行如果他们的 parent 被放弃时所需的清理。