How does Java Garbage collector handle self-reference?

后端 未结 7 717
庸人自扰
庸人自扰 2020-11-27 19:23

Hopefully a simple question. Take for instance a Circularly-linked list:

class ListContainer
{
  private listContainer next;
  <..>

  public void setN         


        
7条回答
  •  情话喂你
    2020-11-27 20:14

    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.

提交回复
热议问题