
原因分析
1、匿名内部类没有被引用的话,匿名内部类的对象用完的话就有回收的机会。
2、如果内部类只是在外部类中引用,当外部类不再引用时,外部类和内部类可以通过GC回收。
内部类引用被外部类以外的其他类引用时,内部类和外部类不能被GC回收,即使外部类不被引用,内部类也有指向外部类的引用)。
实例
publicclassClassOuter{
Objectobject=newObject(){
publicvoidfinalize(){
System.out.println("innerFreetheoccupiedmemory...");
}
};
publicvoidfinalize(){
System.out.println("OuterFreetheoccupiedmemory...");
}
}
publicclassTestInnerClass{
publicstaticvoidmain(String[]args){
try{
Test();
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
privatestaticvoidTest()throwsInterruptedException{
System.out.println("Startofprogram.");
ClassOuterouter=newClassOuter();
Objectobject=outer.object;
outer=null;
System.out.println("ExecuteGC");
System.gc();
Thread.sleep(3000);
System.out.println("Endofprogram.");
}
}
以上就是java内部类的内存泄漏原因,希望对大家有所帮助。更多Java学习指路:Java基础
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END


















































暂无评论内容