16

I have a single spring bean similar to the following:

public class MyServiceImpl {
    private MyDAO myDAO;

    public class MyInnerClass implements SomeInterface<MyInnerClass> {

        @Override
        public MyInnerClass loadFreshObject(final String key) {
            return myDAO.load(key);
        }
    }

}

Instances of MyInnerClass are being created in code outside of the spring bean but no reference to those instances are being kept.

Assuming I have no control over the use of these public non-static inner classes (I know ideally these would be private and static to avoid leaking the reference to 'this'), will the created instances of 'MyInnerClass' be correctly garbage collected?

I have run my own tests on this by overriding the finalize() and it appears that the instances are correctly being garbage collected, I was just hoping for clarification on this.

Thanks

Android Killer
  • 18,174
  • 13
  • 67
  • 90
James Faulkner
  • 271
  • 2
  • 9
  • "*An iterator of a collection is typically implemented as an inner class of the collection.*" helped me understand the relationship between lifetimes of the outer and inner classes. – Franklin Yu Apr 16 '16 at 03:30

4 Answers4

26

Instances of the inner class will be garbage collected according to normal rules (i.e. when they are no longer referenced). However, each instance of the inner class contains a hidden reference to its parent instance of the outer class. This means that if there are any live references to instances of the inner class, they will prevent the associated instances of the outer class from being garbage collected. But it only works in that direction, not the other way around.

Michał Kosmulski
  • 9,855
  • 1
  • 32
  • 51
2

Why wouldn't they garbage collected? The GC doesn't care about the type of an object. If it's unreachable, it's GCed. If it's reachable, it's not GCed.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • That's what I thought, I just wasn't if there was some implicit reference from the outer class to the inner class. – James Faulkner Feb 24 '12 at 10:39
  • No, there isn't. The reverse is true. The non-static inner class contains a reference to its outer class instance. – JB Nizet Feb 24 '12 at 10:40
0

If there are no references to the object, it will be marked for collection. So, it should be fine, even if it is public, non-static inner class.

The other way around i.e. if there were references to these inner class objects, then the outer class object wont be collected, even there are no direct references to it.

Pavan
  • 1,245
  • 7
  • 10
0

Of course, by the way, if your instances are kept by Spring as singleton beans, Spring (but not your code) will keep reference to them and they won't be garbage collected.

Amir Pashazadeh
  • 7,170
  • 3
  • 39
  • 69