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!

1
  • 2
    When the Start constructor is finished both a and b fall out of scope. Commented Sep 24, 2013 at 11:27

2 Answers 2

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.

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

1 Comment

@Oak I have clarified.
1

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

In java when does an object become unreachable?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.