Java 内存泄露的例子

来源:互联网 发布:淘宝客开始怎么拉顾客 编辑:程序博客网 时间:2024/04/28 01:34

第一个例子:

public class MainActivity extends Activity {
       private static Leaky mLeak;    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (mLeak == null) {
            mLeak = new Leak();
        }
    }     
    class Leaky {
        public void hello() {
            System.out.println("hello");
        }
    }
}

原因是内部类含有MainActivity的应用,而mLeak是静态变量,他不制空就会一直有MainActivity的引用。


第二个例子:

private static Drawable sBackground;
@ Override
protected void onCreate (Bundle state) {
super.onCreate (state);
TextView label = new TextView (this); 
label.setText ("Leaks are bad");
the if (sBackground == null) { sBackground = getDrawable (R.drawable.large_bitmap);
} label.setBackgroundDrawable (sBackground);
the setContentView (label);
}
这个原因比较隐蔽,这个Drawable设给VIEW后,VIEW 又将一个callback 设置给了Drawable,所以等于说Drawable 有一个TEXTVIEW的引用,

而TEXTVIEW又有Activity的引用,所以泄露很严重。
                                             
0 0
原创粉丝点击