例1——自动管理内存的类需注意内存泄漏
如下简单的栈结构
class Stack {
private Object[] elements = new Object[16];
private int size = 0;
public void push(Object e) {
elements[size++] = e;
}
public Object pop() {
return elements[--size];
}
}
在以下代码运行后就会出现内存泄漏
Stack stack = new Stack();
stack.push(1);
stack.push(2);
stack.pop();
因为刚刚pop()弹出来的elements[1]已不能通过size寻到并使用,但是栈内部的elements仍保存其引用,而解决办法是将其引用取消并告知虚拟机进行回收,如下修改pop()
public Object pop() {
Object result = elements[--size];
elements[size] = null;
return result;
}
例2——注册的回调需要取消
这在Android中比较常用,在某控件的生命周期结束时,需要将回调取消,如下在onCreate()中注册网络变化的监听事件,在onDestroy()时要取消注册
public class MainActivity extends AppCompatActivity {
private IntentFilter intentFilter;
private NetworkChangeReceiver networkChangeReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
networkChangeReceiver = new NetworkChangeReceiver();
registerReceiver(networkChangeReceiver, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(networkChangeReceiver);
}
private class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isAvailable()) {
Toast.makeText(context, "Network Available", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Network Unavailable", Toast.LENGTH_SHORT).show();
}
}
}
}
|