读书笔记-《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中的键。

猜你喜欢

转载自blog.csdn.net/baitianmingdebai/article/details/85225037