繁体   English   中英

Java内存泄漏理解

[英]Java memory leaks understanding

我已经问过Android上的内存泄漏问题,但我还不知道内存泄漏问题。 现在,我必须保留PhoneStateListener接收到的一些数据。 Singleton模式派上用场,因为我应该保证只有一个实例存在。

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()方法。 我的评论在那里正确吗?

 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(以摆脱不再需要的实例并让垃圾收集器获取它)。

但是,即使您没有这样做,我也不会将其称为“内存泄漏”,因为由于只有一个实例,因此内存泄漏非常有限。 即使未使用,内存消耗也不会随着时间的推移逐渐变大,而通常情况下会出现“泄漏”。

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();
}

该评论不正确。 第一行基本上什么也没做。 您正在更改INSTANCE,使其不再指向旧的PhoneStateInfo,但是分配新的PhoneStateInfo也可以完成相同的任务,即使其不再指向旧的PhoneStateInfo!

您实际上不能从这里确定旧的PhoneStateInfo是否将被垃圾回收。 如果某处的另一段代码创建了对其的引用,则在该引用也消失之前,该代码不符合收集条件。

对于纯Java程序,您的注释不正确。

无需为对象设置null以将其标记为可用于GC。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM