How does Java solve retain cycles in garbage collection?

garbage-collection, java

Solution

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.

Problem

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 `weak`. From what I have read and understood, the Java GC is not affected by retain cycles, and we do not have to worry about `weak` references. How does it solve it?

Original source

Related problems