
原因分析
1、匿名内部类没有被引用的话,匿名内部类的对象用完的话就有回收的机会。
2、如果内部类只是在外部类中引用,当外部类不再引用时,外部类和内部类可以通过GC回收。
内部类引用被外部类以外的其他类引用时,内部类和外部类不能被GC回收,即使外部类不被引用,内部类也有指向外部类的引用)。
实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 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内部类的内存泄漏原因,希望对大家有所帮助。更多Java学习指路:Java基础
本教程操作环境:windows7系统、java10版,DELL G3电脑。