读书笔记-《Effective Java》第6条:消除过期的对象引用

内存泄漏的三种可能

1. 类自己管理内存,一旦元素被释放掉,则该元素中包含的任何对象引用都应该被清空。

例如:ArrayList类的remove方法。  elementData[--size] = null; // clear to let GC do its work

/**
     * Removes the element at the specified position in this list.
     * Shifts any subsequent elements to the left (subtracts one from their
     * indices).
     *
     * @param index the index of the element to be removed
     * @return the element that was removed from the list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E remove(int index) {
        rangeCheck(index);

        modCount++;
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }

2. 来自缓存

用框架里面的缓存就大概不会有问题吧,都有各种清除策略,专门研究缓存的时候再细看。

3. 监听器和其他回调(看不懂,先抄下来)

原文:如果你实现了一个API,客户端在这个API中注册回调,却没有显式的地取消注册,那么除非你采取某些动作,否则它们就会聚积。确保回调立即被当做垃圾回收的最佳方法是只保存它们的弱引用(weak reference),例如,只将它们保存成WeakHashMap中的键。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值