Sobes.tech
Junior — Middle

What are the consequences if two objects in Java hold references to each other using strong references?

sobes.tech AI

Answer from AI

If two objects in Java hold strong references to each other, a situation called a cyclic reference occurs. In the standard Java garbage collector (GC), this does not lead to a memory leak because GC uses reachability algorithms: if objects are unreachable from root references (such as from the stack or static variables), they will be collected, even if they reference each other.

However, if objects are in an active reachability scope, they will not be removed, which can lead to increased memory consumption.

Unlike some other reference-counted languages (e.g., Objective-C), cyclic references are not a problem for Java's garbage collector.

Example:

class A {
    B b;
}
class B {
    A a;
}

// If objects a and b reference each other but are unreachable from the root, GC will delete them.
What are the consequences if two objects in Java hold… - sobes.tech