Java垃圾收集器如何处理自引用? [英] How does Java Garbage collector handle self-reference?

查看:100
本文介绍了Java垃圾收集器如何处理自引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望有一个简单的问题。以一个循环链表为例:

  class ListContainer 
{
private listContainer next;
< ..>

public void setNext(listContainer next)
{
this.next = next;
}
}

class列表
{
private listContainer entry;
< ..>





$ b现在,由于它是一个循环链表,当添加单个元素时,它在下一个变量中有一个参考。删除列表中唯一的元素时,条目设置为空。是否需要将ListContainer.next设置为null以便垃圾收集器释放它的内存,或者它是否自动处理这种自引用?

解决方案 div>

只依靠引用计数的垃圾收集器通常很容易无法收集像这样的自引用结构。这些GC依赖于对该对象引用次数的计数,以便计算给定对象是否可到达。



非引用计数方法应用更全面的可访问性测试以确定对象是否有资格被收集。这些系统定义了一个始终被认为是可达的对象(或一组对象)。任何可从此对象图中获得引用的对象都被认为不适合收集。不能直接从这个对象访问的对象不是。因此,周期不会影响可达性,并且可以收集。

另请参阅追踪垃圾收集器


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垃圾收集器如何处理自引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆