How does Java solve retain cycles in garbage collection?

后端 未结 4 846
别那么骄傲
别那么骄傲 2021-02-04 06:33

I know that a retain cycle (at least in Objective-C and Swift) is when two objects claim ownership of one another (they have references to each other). And in Objective-C we can

4条回答
  •  无人及你
    2021-02-04 07:19

    The Java (JVM) garbage collector works by looking for "reachable" objects - from the root(s) of the object tree. If they can't be reached (if they have no outside object references) then entire object graphs can be discarded.

    Essentially it just just traverses the tree from root(s) to leaf nodes and marks all objects it encounters. Any memory not taken up by marked objects in the heap is swept (marked as free). This is called mark and sweep. img src

    This can't be done easily in objective-c because it uses reference counting, not mark and sweep which has it's flaws

    The reason there can be no retain cycles is because if they aren't linked to the "tree" anywhere, they aren't marked and can be discarded.

提交回复
热议问题