Android LruCache究竟是什么

源码: /frameworks/base/core/java/android/util/LruCache.java

文件开篇注释如下: 

A cache that holds strong references to a limited number of values. Each time a value is accessed, it is moved to the head of a queue. When a value is added to a full cache, the value at the end of that queue is evicted and may become eligible for garbage collection.

含义是:

    一个只对有限个value保持强引用的Cache.

    每次访问一个value, 它都会被移到队头.

    当一个Cache满了之后, 如果再向它添加元素, 队尾的元素将会被回收.

<p>If your cached values hold resources that need to be explicitly released, override {@link #entryRemoved}.

    如果有一个元素需要被显式的释放, 重写entryRemoved方法

    protected void entryRemoved(boolean evicted, K key, V oldValue, V newValue) {}


<p>If a cache miss should be computed on demand for the corresponding keys,override {@link #create}. 
This simplifies the calling code, allowing it to assume a value will always be returned, even when there's a cache miss.

    对这段理解的一直不是很好, 读完源码以后再说

    protected V create(K key) {
        return null;
    }
<p>This class does not allow null to be used as a key or value. 
A return value of null from {@link #get}, {@link #put} or {@link #remove} is unambiguous: the key was not in the cache.

     这个类不允许Key 和 Value 是 null. 如果 get, put, remove中出现了null, 那么将会返回 该Cache中不存在这个key 

关键代码:

public class LruCache<K, V> {
    private final LinkedHashMap<K, V> map;

    /** Size of this cache in units. Not necessarily the number of elements. */
    private int size;
    private int maxSize;

    private int putCount;
    private int createCount;
    private int evictionCount;
    private int hitCount;
    private int missCount;

    /**
     * @param maxSize for caches that do not override {@link #sizeOf}, this is
     *     the maximum number of entries in the cache. For all other caches,
     *     this is the maximum sum of the sizes of the entries in this cache.
     */
    public LruCache(int maxSize) {
        if (maxSize <= 0) {
            throw new IllegalArgumentException("maxSize <= 0");
        }
        this.maxSize = maxSize;
        this.map = new LinkedHashMap<K, V>(0, 0.75f, true);
    }
}

    使用 LinkedHashMap来管理整个Cache

使用 LruCache 必须重写 sizeOf 方法, sizeOf方法用来计算 value的大小

    protected int sizeOf(K key, V value) {
        return 1;
    }

使用方法

        // 继承LruCache时,必须要复写sizeof方法,用于计算每个条目的大小
        // cacheMemory 表示可用缓存的大小, value 也不能超出 cacheMemory
        mLruCache = new LruCache<String, Bitmap>(cacheMemory) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount();
            }
        };
原文地址:https://www.cnblogs.com/carlo/p/4963618.html