我已经问过memory leaks on Android了,但我对内存泄漏还不是很了解。现在,我必须保存PhoneStateListener接收到的一些数据。单例模式很方便,因为我应该保证只有一个实例存在。
public class PhoneStateInfo {
/** -1 until the first reception */
private int mCid = -1;
/** -1 until the first reception */
private int mLac = -1;
/** 0 until the first reception */
private int mMcc;
/** 0 until the first reception */
private int mMnc;
// And so on...
private static PhoneStateInfo INSTANCE = new PhoneStateInfo();
public static PhoneStateInfo getInstance() {
return INSTANCE;
}
private PhoneStateInfo() {}
/**
* Reverts the single instance to its initial state
* But if I have 10 or 20 fields which have various default values, it will be easy to forget something
*/
void clear() {
mCid = -1;
mLac = -1;
mMcc = 0;
mMnc = 0;
mRssi = -1;
mSimState = TelephonyManager.SIM_STATE_UNKNOWN;
mDeviceId = null;
mSubscriberId = null;
mPhoneNumber = null;
}
/**
* Reverts the single instance to its initial state
* Short and clear
*/
static void clearInstance() {
INSTANCE = null; // If I delete this line, memory leaks will occur
// because the old reference is left alive will not be garbage-collected
INSTANCE = new PhoneStateInfo();
}
}请参考clear()和clearInstance()方法。我的评论是正确的吗?
发布于 2013-06-05 00:46:20
INSTANCE = null; // If I delete this line, memory leaks will occur
// because the old reference is left alive will not be garbage-collected
INSTANCE = new PhoneStateInfo();这不是真的。
在将字段赋值给新值之前,不必将该字段设置为null。您可以使用新值覆盖它。
如果没有新值,您可能希望将其设置为null (以删除不再需要的实例,并让垃圾收集器处理它)。
但是即使你没有,我也不会叫它“内存泄漏”,因为它只有一个实例,所以它是非常有限的。即使不使用,内存消耗也不会随着时间的推移而逐渐变大,这通常会导致“泄漏”。
发布于 2013-06-05 00:43:44
static void clearInstance() {
INSTANCE = null; // If I delete this line, memory leaks will occur
// because the old reference is left alive will not be garbage-collected
INSTANCE = new PhoneStateInfo();
}这条评论是不正确的。第一行基本上什么也不做。您正在将实例更改为不再指向旧的PhoneStateInfo,但是分配一个新的PhoneStateInfo也会完成相同的任务,即使其不再指向旧的are!
从这里你不能确定旧的PhoneStateInfo是否会被垃圾回收。如果另一段代码在某处创建了对它的引用,那么在该引用也被删除之前,它是不符合收集条件的。
发布于 2013-06-05 00:45:53
但是如果你的程序使用的是自定义的ClassLoaders,WeakReference,ThreadLocals,它可能会泄漏。
https://stackoverflow.com/questions/16923051
复制相似问题