How does Java Garbage Collection work with Circular References?

后端 未结 8 1709
旧时难觅i
旧时难觅i 2020-11-22 04:53

From my understanding, garbage collection in Java cleans up some objects if nothing else is \'pointing\' to that object.

My question is, what happens if we have some

8条回答
  •  感情败类
    2020-11-22 05:38

    yes Java Garbage collector handles circular-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.

    Ofcourse sometimes this may led to memory leak if programmer forgets to dereference an object.

    enter image description here

    Source : Java Memory Management

提交回复
热议问题