2

I have 2 classes and both of them hold a reference to the other.

class A { private B b; public A(B b) { this.b = b; } } class B { private A a; public B() { a = new A(this); } } 

If it leaks memory, then how I can achieve what I want without leaking?

3
  • 2
    Define leak memory. Why do you think this code does that or why do you think it doesn't? Commented May 2, 2016 at 15:57
  • I think that B couldn't be cleaned, because A holds a reference to it, but A couldn't be cleaned, because A holds a reference to it, so A and B never get garbage collected. Commented May 2, 2016 at 15:59
  • 2
    Generally speaking, you never have to worry about memory leaks in Java. It does its own garbage collection and keeps up with objects when they are no longer referenced so that it can delete them safely. It's one of the perks with java. Commented May 2, 2016 at 16:00

1 Answer 1

5

Java's GC is smart enough to deal with circular references, it starts from GC roots down to objects to check if they are still alive or not. So if you have an object of type A that is not referenced from anywhere ( ie: GC root) it will be eligible for garbage collection even if it references B.

A circular linked list does something similar all the time.

Sign up to request clarification or add additional context in comments.

1 Comment

I didn't know about that, but this is a well detailed clarifying.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.