7

Lets assume that some class is not reachable, but there are another anonymous classes generated by the class which are reachable. Could the first one be removed by the Garbage Collector?

Example:


class Outer {
  public Object getInner() {
    return new Object() {};
  }
}

...

Outer outer = new Outer();
Object inner = outer.getInner();

// Could the "outer" instance be removed here considering that "inner" is using below?
Ilya Lakhin
  • 1,904
  • 1
  • 16
  • 31
  • In your code you are calling a method from the `Outer` class. What can possibly be unreachable there? – Marcelo Mar 02 '12 at 09:39

1 Answers1

8

No, the outer instance is still reachable in this case, since every non-static inner class has an implicit rerefence to its outer class instance.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • The difference is that anonymous class in my example does not use its reference to the outer class explicitly(neither internally nor externally). So I think that actually outer class is not reachable. – Ilya Lakhin Mar 02 '12 at 09:52
  • 5
    It still has the reference. And the JVM is unable to know that this reference will never be used. If you never use this outer reference, the class should be a static inner class, or a top-level class. – JB Nizet Mar 02 '12 at 09:56