非静态内部类对象在不再被引用后是否被垃圾收集? [英] Are non-static inner class objects garbage collected after they are no longer referenced?

查看:93
本文介绍了非静态内部类对象在不再被引用后是否被垃圾收集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public class MyServiceImpl {
private MyDAO myDAO;

public class MyInnerClass implements SomeInterface< MyInnerClass> {

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



$ b $ / code>

实例在Spring bean之外的代码中创建 MyInnerClass ,但没有引用这些实例。假设我无法控制这些公共的非静态内部类的使用(我知道理想情况下这些是私有的和静态的,以避免泄漏对'this'的引用, ),创建的'MyInnerClass'实例是否被正确地垃圾收集?



我通过覆盖 finalize()来运行我自己的测试,看起来这些实例是正确的被垃圾收集,我只是希望澄清这一点。



谢谢

解决方案

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

解决方案

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.

这篇关于非静态内部类对象在不再被引用后是否被垃圾收集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆