I have a class A:
public class A {
private B b = new B() { public void method() { do something } };
public B getB() { return b; }
}
public interface B { void method(); }
The instance b has an implicit reference of the instance of its outer class (that can be referenced by this). Now another object gets a reference to this b via the getter method. This b cannot be garbage collected due to the reference.
Is there a way to get a possibility to allow a garbage collection of the enclosing A instance, maybe via resetting an explicit reference in the anonymous inner class?
It is technically possible:
The javap inspection of the anonymous class:
The implementation does not rely on the field name being
this$0as I suspect this is a compiler implementation detail.Potential problem areas:
In short, I would never do this.
If this is a concern, use a private static inner class: