1

Assume Outer is instantiated somewhere, and after a while there are no references to it. Does the implicit reference in inner to the Outer instance prevent GC from running, or does the is it a "special" reference?

public class Outer {
    private class Inner extends Something {}

    private Inner inner = new Inner();
}
1

1 Answer 1

3

If the instance of Outer is not reachable from a GC root, the reference to an Inner instance in your example code will not stop the garbage collector from freeing the memory the Outer used.

Consider this diagram:

Stack of main thread           public static void main(String[] args) {
         |                       Outer outer = new Outer();
         v                     
       Outer<--\
         |\    |
         v \---/
       Inner 

Stack of main thread               outer = new Outer();
         |
         v          
       Outer<--\
         |\ new|
         v \---/
       Inner 

       Outer<--\                   // a reference to the Outer from the Inner
         |\ old|                   // doesn't change the fact that the Outer
         v \---/                   // can't be reached from a GC root.
       Inner                       // Thus the old Outer is eligible for collection (dead)
Sign up to request clarification or add additional context in comments.

3 Comments

Just to clarify, since there are no references to Outer besides for one from "inside" itself, it is eligible for GC?
Not quite, it is eligible for GC under the assertion you made in your question "and after a while there are no references to it [Outer]"
Yes, that's what I meant. I should have been more explicit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.