Android缓存机制——LruCache

概述

LruCache的核心原理就是对LinkedHashMap的有效利用,它的内部存在一个LinkedHashMap成员变量,值得注意的4个方法:构造方法、get、put、trimToSize

LRU(Least Recently Used)缓存算法便应运而生,LRU是最近最少使用的算法,它的核心思想是当缓存满时,会优先淘汰那些最近最少使用的缓存对象。采用LRU算法的缓存有两种:LrhCache和DisLruCache,分别用于实现内存缓存和硬盘缓存,其核心思想都是LRU缓存算法。

 

LRU原理

LruCache的核心思想很好理解,就是要维护一个缓存对象列表,其中对象列表的排列方式是按照访问顺序实现的,即一直没访问的对象,将放在队头,即将被淘汰。而最近访问的对象将放在队尾,最后被淘汰。(队尾添加元素,队头删除元素)

LruCache 其实使用了 LinkedHashMap 双向链表结构,现在分析下 LinkedHashMap 使用方法。

1.构造方法:

 

public LinkedHashMap(int initialCapacity,
    float loadFactor,
    boolean accessOrder) {
    super(initialCapacity, loadFactor);
    this.accessOrder = accessOrder;
}

 

 当 accessOrder 为 true 时,这个集合的元素顺序就会是访问顺序,也就是访问了之后就会将这个元素放到集合的最后面。

 例如:

LinkedHashMap < Integer, Integer > map = new LinkedHashMap < > (0, 0.75f, true);
map.put(0, 0);
map.put(1, 1);
map.put(2, 2);
map.put(3, 3);
map.get(1);
map.get(2);

for (Map.Entry < Integer, Integer > entry: map.entrySet()) {
    System.out.println(entry.getKey() + ":" + entry.getValue());

}

 

输出结果:

0:0
3:3
1:1
2:2

 

下面我们在LruCache源码中具体看看,怎么应用LinkedHashMap来实现缓存的添加,获得和删除的:

/**
     * @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);//accessOrder被设置为true
    }

 

从LruCache的构造函数中可以看到正是用了LinkedHashMap的访问顺序。

2.put()方法

 

/**
     * Caches {@code value} for {@code key}. The value is moved to the head of
     * the queue.
     *
     * @return the previous value mapped by {@code key}.
     */
    public final V put(K key, V value) {
        if (key == null || value == null) {//判空,不可为空
            throw new NullPointerException("key == null || value == null");
        }

        V previous;
        synchronized (this) {
            putCount++;//插入缓存对象加1
            size += safeSizeOf(key, value);//增加已有缓存的大小
            previous = map.put(key, value);//向map中加入缓存对象
            if (previous != null) {//如果已有缓存对象,则缓存大小恢复到之前
                size -= safeSizeOf(key, previous);
            }
        }

        if (previous != null) {//entryRemoved()是个空方法,可以自行实现
            entryRemoved(false, key, previous, value);
        }

        trimToSize(maxSize);//调整缓存大小(关键方法)
        return previous;
    }

 

 可以看到put()方法重要的就是在添加过缓存对象后,调用 trimToSize()方法来保证内存不超过maxSize

3.trimToSize方法

再看一下trimToSize()方法:

 /**
     * Remove the eldest entries until the total of remaining entries is at or
     * below the requested size.
     *
     * @param maxSize the maximum size of the cache before returning. May be -1
     *            to evict even 0-sized elements.
     */
    public void trimToSize(int maxSize) {
        while (true) {//死循环
            K key;
            V value;
            synchronized (this) {
         //如果map为空并且缓存size不等于0或者缓存size小于0,抛出异常
if (size < 0 || (map.isEmpty() && size != 0)) { throw new IllegalStateException(getClass().getName() + ".sizeOf() is reporting inconsistent results!"); }           //如果缓存大小size小于最大缓存,或者map为空,不需要再删除缓存对象,跳出循环 if (size <= maxSize) { break; }           // 取出 map 中最老的映射 Map.Entry<K, V> toEvict = map.eldest(); if (toEvict == null) { break; } key = toEvict.getKey(); value = toEvict.getValue(); map.remove(key); size -= safeSizeOf(key, value); evictionCount++; } entryRemoved(true, key, value, null); } }

 

 

trimToSize()方法不断地删除LinkedHashMap中队头的元素,即近期最少访问的,直到缓存大小小于最大值。

4. get方法

当调用LruCache的get()方法获取集合中的缓存对象时,就代表访问了一次该元素,将会更新队列,保持整个队列是按照访问顺序排序。这个更新过程就是在LinkedHashMap中的get()方法中完成的。

接着看LruCache的get()方法

 

 /**
     * Returns the value for {@code key} if it exists in the cache or can be
     * created by {@code #create}. If a value was returned, it is moved to the
     * head of the queue. This returns null if a value is not cached and cannot
     * be created.
     */
    public final V get(K key) {
        if (key == null) {//key不能为空
            throw new NullPointerException("key == null");
        }

        V mapValue;
        synchronized (this) {
        /获取对应的缓存对象 mapValue
= map.get(key); if (mapValue != null) { hitCount++; return mapValue; } missCount++; }

 

 看到LruCache的get方法实际是调用了LinkedHashMap的get方法:

public V get(Object key) {
        LinkedHashMapEntry<K,V> e = (LinkedHashMapEntry<K,V>)getEntry(key);
        if (e == null)
            return null;
        e.recordAccess(this);//实现排序的关键
        return e.value;
    }

 

 再接着看LinkedHashMapEntry的recordAccess方法:

     /**
         * This method is invoked by the superclass whenever the value
         * of a pre-existing entry is read by Map.get or modified by Map.set.
         * If the enclosing Map is access-ordered, it moves the entry
         * to the end of the list; otherwise, it does nothing.
         */
        void recordAccess(HashMap<K,V> m) {
            LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;
            if (lm.accessOrder) {//判断是否是访问顺序
                lm.modCount++;
                remove();//删除此元素
                addBefore(lm.header);//将此元素移到队尾
            }
        }

 

recordAccess方法的作用是如果accessOrder为true,把已存在的entry在调用get读取或者set编辑后移到队尾,否则不做任何操作。

也就是说: 这个方法的作用就是将刚访问过的元素放到集合的最后一位

 

5.总结:

LruCache的核心原理就是对LinkedHashMap 对象的有效利用。在构造方法中设置maxSize并将accessOrder设为true,执行get后会将访问元素放到队列尾,put操作后则会调用trimToSize维护LinkedHashMap的大小不大于maxSize。

 

 参考:https://juejin.im/post/5b5d4e2d6fb9a04fc226c09f  ; https://www.cnblogs.com/ganchuanpu/p/8908264.html

 

posted @ 2019-04-27 23:03  Ivo-oo  阅读(761)  评论(0编辑  收藏  举报