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?

Ukubu
  • 810
  • 1
  • 6
  • 18
  • 2
    Define _leak memory_. Why do you think this code does that or why do you think it doesn't? – Sotirios Delimanolis May 02 '16 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. – Ukubu May 02 '16 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. – Rabbit Guy May 02 '16 at 16:00

1 Answers1

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.

Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77