How does java GC clean inter related object

前端 未结 2 1846
余生分开走
余生分开走 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.

    0 讨论(0)
  • 2021-01-28 18:38

    There is a number of GCs. In the Young Generation, there is a copy collector.

    What this does is find all the objects which are referenced from "root" objects such a thread stacks. e.g. the eden space is copied to a survivor space, and the survivor spaces are copied to each other. Anything left uncopied is cleared away.

    This means if you have a bundle of objects which refer to each other and there is no strong reference to any of them, they will be discarded on the next collection. (The exception being soft references where the GC can choose to keep them or not)

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