How does Java Garbage collector handle self-reference?(Java 垃圾收集器如何处理自引用?)
问题描述
希望是一个简单的问题.以循环链表为例:
类 ListContainer{下一个私有列表容器;<..>public void setNext(listContainer next){this.next = 下一个;}}班级名单{私有列表容器条目;<..>}
现在因为它是一个循环链表,当添加一个元素时,它在下一个变量中具有对自身的引用.删除列表中的唯一元素时,条目设置为 null.是否需要将 ListContainer.next 设置为 null 以及垃圾收集器以释放其内存还是自动处理此类自引用?
仅依赖引用计数的垃圾收集器通常容易无法收集此类自引用结构.这些 GC 依赖于对该对象的引用次数的计数,以计算给定对象是否可访问.
非引用计数方法应用更全面的可达性测试来确定对象是否有资格被收集.这些系统定义了一个总是被认为是可达的对象(或一组对象).可以从此对象图中获得引用的任何对象都被认为不符合收集条件.不能从该对象直接访问的任何对象都不是.因此,循环最终不会影响可达性,并且可以被收集.
另请参阅跟踪垃圾收集器的维基百科页面.p>
Hopefully a simple question. Take for instance a Circularly-linked list:
class ListContainer
{
private listContainer next;
<..>
public void setNext(listContainer next)
{
this.next = next;
}
}
class List
{
private listContainer entry;
<..>
}
Now since it's a circularly-linked list, when a single elemnt is added, it has a reference to itself in it's next variable. When deleting the only element in the list, entry is set to null. Is there a need to set ListContainer.next to null as well for Garbage Collector to free it's memory or does it handle such self-references automagically?
Garbage collectors which rely solely on reference counting are generally vulnerable to failing to collection self-referential structures such as this. These GCs rely on a count of the number of references to the object in order to calculate whether a given object is reachable.
Non-reference counting approaches apply a more comprehensive reachability test to determine whether an object is eligible to be collected. These systems define an object (or set of objects) which are always assumed to be reachable. Any object for which references are available from this object graph is considered ineligible for collection. Any object not directly accessible from this object is not. Thus, cycles do not end up affecting reachability, and can be collected.
See also, the Wikipedia page on tracing garbage collectors.
这篇关于Java 垃圾收集器如何处理自引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 垃圾收集器如何处理自引用?


基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01