1

I wondered what would happen with this example code:

public class Start {
    public static void main(String[] args) {
        new Start().go();
    }

    public Start() {
        A a = new A();
        B b = new B();
        a.setB(b);
        b.setA(a);
    }

    public boolean running = true;

    public void go() {
        while( running ) {
             try {
                 Thread.sleep(10);
             } catch ( Throwable t ) {}
        }
    }
}

public class A {
    B b;
    public void setB(B b) {
        this.b = b;
    }
}

public class B {
    A a;
    public void setA(A a) {
        this.a = a;
    }
}

It is obviously a stupid program, but: I wandered what would happen to the instances of A and B? They both are referred to by each other, so they shouldn't be considered collectable. But in fact, they ARE dead to the rest of the program, for they will never be referenced to again.

So my question is would they be garbage collected? Or are they dead memory?

Thanks in advance!

Jakunar
  • 156
  • 1
  • 2
  • 7

2 Answers2

6

Once Start's constructor is over, the two references a and b are not reachable by any "roots" so they become eligible to garbage collection. Roots are typically variables on the call stack or global variables.

Some garbage collectors (e.g. those that use reference counting) can have difficulties with cyclic references but modern GCs can deal with that type of situation without problem.

assylias
  • 321,522
  • 82
  • 660
  • 783
1

They get collected by the garbage collector because they are not reachable any more.

In java when does an object become unreachable?

Community
  • 1
  • 1
isnot2bad
  • 24,105
  • 2
  • 29
  • 50