How does java GC clean inter related object

前端 未结 2 1847
余生分开走
余生分开走 2021-01-28 17:42

Could anyone please tell me what will be with objects that refer to each other? How does java\'s GC resolve that issue? Thanks in advance!

2条回答
  •  孤独总比滥情好
    2021-01-28 18:25

    If you have object A and B, and if the following conditions hold:

    • A references to B
    • B references to A
    • No other objects reference to any one of them
    • They are not root objects (e.g. objects in the constants pool etc)

    then, these two objects will be garbage collected. This is called "circular reference".

    This is because the mark-and-sweep GC will scan and find out all the objects that are reachable from the root objects. If A and B reference each other without any external reference, the mark-and-sweep GC won't be able to mark them as reachable, hence will be selected as candidates for GC.

    There are a number of different mark-and-sweep implementations (naive mark-and-sweep, tri-colour etc). But the fundamental idea is the same. If an object cannot be reached from the root by direct/indirect references, it will be garbage collected.

提交回复
热议问题