Java 垃圾收集器如何处理自引用?

2022-01-16 00:00:00 garbage-collection 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.

相关文章