How does Java Garbage collector handle self-reference?

后端 未结 7 693
庸人自扰
庸人自扰 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:19

    yes Java Garbage collector handle self-reference!

    How?
    

    There are special objects called called garbage-collection roots (GC roots). These are always reachable and so is any object that has them at its own root.

    A simple Java application has the following GC roots:

    1. Local variables in the main method
    2. The main thread
    3. Static variables of the main class

    enter image description here

    To determine which objects are no longer in use, the JVM intermittently runs what is very aptly called a mark-and-sweep algorithm. It works as follows

    1. The algorithm traverses all object references, starting with the GC roots, and marks every object found as alive.
    2. All of the heap memory that is not occupied by marked objects is reclaimed. It is simply marked as free, essentially swept free of unused objects.

    So if any object is not reachable from the GC roots(even if it is self-referenced or cyclic-referenced) it will be subjected to garbage collection.

    0 讨论(0)
提交回复
热议问题