您的位置:首页 >java内部类内存泄漏的原因是什么
发布于2023-04-24 阅读(0)
扫一扫,手机访问
原因分析
1、匿名内部类没有被引用的话,匿名内部类的对象用完的话就有回收的机会。
2、如果内部类只是在外部类中引用,当外部类不再引用时,外部类和内部类可以通过GC回收。
内部类引用被外部类以外的其他类引用时,内部类和外部类不能被GC回收,即使外部类不被引用,内部类也有指向外部类的引用)。
实例
public class ClassOuter {
Object object = new Object() {
public void finalize() {
System.out.println("inner Free the occupied memory...");
}
};
public void finalize() {
System.out.println("Outer Free the occupied memory...");
}
}
public class TestInnerClass {
public static void main(String[] args) {
try {
Test();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void Test() throws InterruptedException {
System.out.println("Start of program.");
ClassOuter outer = new ClassOuter();
Object object = outer.object;
outer = null;
System.out.println("Execute GC");
System.gc();
Thread.sleep(3000);
System.out.println("End of program.");
}
} 下一篇:Java类变量和类方法实例分析
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9