Anders Anders - 1 year ago 145
Java Question

Java retain cycle (garbage collection)

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 solve the issue by declaring one of them


From what I have read and understood, the Java GC is not affected by retain cycles, and we do not have to worry about
references. How does it solve it?

Answer Source

The Java garbage collector works by looking for "reachable" objects - from the root(s). 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 stem and marks all objects it encounters. Any memory not taken up by marked objects in the heap is sweeped (marked as free). This is called mark and sweep.

This can't be done easily in 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download