Search code examples
javamemory-leaksgarbage-collection

Does Composite object's reciprocal relationship cause memory leak in java


Suppose we have following case. Should we face any memory leak here?

class A {
   B b;
   void set(B in) { b = in; }
}

class B {
  A a;
  void set(A in) { a = in; }
}

void main() {
   A ina = new A();
   B inb = new B();
   ina.set(inb);
   inb.set(ina);
}

Solution

  • By itself, circular dependency can not cause memory leak in Java. Not sure whether that simply answers your question, you can take a look at the following for further discussions and explanations.

    Java: Is it bad practice to have a circular dependency within the same package?

    Will this cause memory leak