gpt4 book ai didi

java - java中虚引用的重要性

转载 作者:行者123 更新时间:2023-12-01 11:19:54 25 4
gpt4 key购买 nike

我想理解下面粗体的陈述。这是什么意思? (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.

幻象引用解决了什么问题

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 方法不会在其关联对象被垃圾收集时触发,而是在其关联对象本来会被垃圾收集时触发,但对于它们的非默认 finalize 方法的存在。在系统 100% 确定永远不会存在对对象的引用之前,对象实际上无法被垃圾收集,但是运行 finalize 方法的行为会创建一个强大的根对相关对象的引用,该对象至少在方法退出之前一直存在。如果在执行finalize期间,对对象的引用存储在其他地方,则该引用可能会无限期地继续存在。因此,在 finalize 之后之前,无法收集将要调用其 finalized 方法的对象,也无法收集该对象持有直接或间接强引用的任何其他对象。 > 方法已运行,下一个 GC 周期确认不再存在对该对象的引用。

PhantomReference 类用于封装不同的范例:而不是让对象保持 Activity 状态,以便系统可以通知它它已被放弃,而它仍然 Activity 的唯一原因是它可以接收以下通知:放弃,需要清理的对象应该创建辅助对象来处理放弃的通知。如果辅助对象避免保留对它们不“拥有”的任何外部对象的引用,则它们的存在不会干扰其父对象或父对象直接或间接引用的其他对象的集合。辅助对象通常不会保存足够的信息来让它们“做很多事情”,但这很好,因为它们不必做太多事情。相反,他们的设计应该侧重于执行在其父级被遗弃时所需的清理工作。

关于java - java中虚引用的重要性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31372036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com