Java – non static inner class objects are garbage collected after they are no longer referenced?

I have a 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 spring beans, but references to these instances are not retained

Assuming that I cannot control the use of these public non static internal classes (I understand that these will be private and static to avoid disclosing references to 'this'), is the created "myinnerclass" instance properly garbage collected?

I've run my own tests by overriding finalize () and it looks like the instance is being garbage collected. I just want to clarify this

thank you

Solution

Instances of inner classes are garbage collected according to normal rules (that is, they are no longer referenced) However, each instance of an inner class contains a hidden reference to the parent instance of its outer class This means that if there are real-time references to instances of inner classes, they will prevent the associated instances of outer classes from being garbage collected But it can only work in this direction, not the opposite

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>