首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java内存泄漏了解

Java内存泄漏了解
EN

Stack Overflow用户
提问于 2013-06-05 00:33:06
回答 3查看 158关注 0票数 0

我已经问过memory leaks on Android了,但我对内存泄漏还不是很了解。现在,我必须保存PhoneStateListener接收到的一些数据。单例模式很方便,因为我应该保证只有一个实例存在。

代码语言:javascript
复制
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()方法。我的评论是正确的吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-06-05 00:46:20

代码语言:javascript
复制
 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 (以删除不再需要的实例,并让垃圾收集器处理它)。

但是即使你没有,我也不会叫它“内存泄漏”,因为它只有一个实例,所以它是非常有限的。即使不使用,内存消耗也不会随着时间的推移而逐渐变大,这通常会导致“泄漏”。

票数 3
EN

Stack Overflow用户

发布于 2013-06-05 00:43:44

代码语言:javascript
复制
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是否会被垃圾回收。如果另一段代码在某处创建了对它的引用,那么在该引用也被删除之前,它是不符合收集条件的。

票数 1
EN

Stack Overflow用户

发布于 2013-06-05 00:45:53

但是如果你的程序使用的是自定义的ClassLoadersWeakReferenceThreadLocals,它可能会泄漏。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16923051

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档