How does Java Garbage Collection work with Circular References?

后端 未结 8 1856
旧时难觅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:36

    The Java GCs don't actually behave as you describe. It's more accurate to say that they start from a base set of objects, frequently called "GC roots", and will collect any object that can not be reached from a root.
    GC roots include things like:

    • static variables
    • local variables (including all applicable 'this' references) currently in the stack of a running thread

    So, in your case, once the local variables a, b, and c go out of scope at the end of your method, there are no more GC roots that contain, directly or indirectly, a reference to any of your three nodes, and they'll be eligible for garbage collection.

    TofuBeer's link has more detail if you want it.

提交回复
热议问题