LruCache原理

LruCache(Least Recently Used)算法的核心思想就是最近最少使用算法。
他在算法的内部维护了一个LinkHashMap的链表,通过put数据的时候判断是否内存已经满了,
如果满了,则将最近最少使用的数据给剔除掉,从而达到内存不会爆满的状态。

一. LruCache基本原理

LRU全称为Least Recently Used,即最近最少使用。由于缓存容量是有限的,当有新的数据需要加入缓存,但缓存的空闲空间不足的时候,如何移除原有的部分数据从而释放空间用来存放新的数据。
LRU算法就是当缓存空间满了的时候,将最近最少使用的数据从缓存空间中删除以增加可用的缓存空间来缓存新数据。这个算法的内部有一个缓存列表,每当一个缓存数据被访问的时候,这个数据就会被提到列表尾部,每次都这样的话,列表的头部数据就是最近最不常使用的了,当缓存空间不足时,就会删除列表头部的缓存数据。

二. LruCache的使用

//获取系统分配给每个应用程序的最大内存
int maxMemory=(int)(Runtime.getRuntime().maxMemory()/1024);
int cacheSize=maxMemory/8;
private LruCache mMemoryCache;
//给LruCache分配1/8
mMemoryCache = new LruCache(mCacheSize){  
    //重写该方法,来测量Bitmap的大小  
    @Override  
    protected int sizeOf(String key, Bitmap value) {  
        return value.getRowBytes() * value.getHeight()/1024;  
    }  
};

三. LruCache部分源码解析

LruCache 利用 LinkedHashMap 的一个特性(accessOrder=true 基于访问顺序)再加上对 LinkedHashMap 的数据操作上所实现的缓存策略。
LruCache 的数据缓存是内存中的。
*
首先设置了内部 LinkedHashMap 构造参数 accessOrder=true, 实现了数据排序按照访问顺序。
*
LruCache类在调用get(K key) 方法时,都会调用LinkedHashMap.get(Object key) 。
*
如上述设置了 accessOrder=true 后,调用LinkedHashMap.get(Object key) 都会通过LinkedHashMap的afterNodeAccess()方法将数据移到队尾。
*
由于最新访问的数据在尾部,在 put 和 trimToSize 的方法执行下,如果发生数据移除,会优先移除掉头部数据

1.构造方法

/**
     * @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(0, 0.75f, true);
        }
2.添加数据 LruCache.put(K key, V value)
/**
     * 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++;
             //safeSizeOf(key, value)。
             //这个方法返回的是1,也就是将缓存的个数加1.
            // 当缓存的是图片的时候,这个size应该表示图片占用的内存的大小,所以应该重写里面调用的sizeOf(key, value)方法
            size += safeSizeOf(key, value);
            //向map中加入缓存对象,若缓存中已存在,返回已有的值,否则执行插入新的数据,并返回null
            previous = map.put(key, value);
            //如果已有缓存对象,则缓存大小恢复到之前
            if (previous != null) {
                size -= safeSizeOf(key, previous);
            }
        }
          //entryRemoved()是个空方法,可以自行实现
        if (previous != null) {
            entryRemoved(false, key, previous, value);
        }

        trimToSize(maxSize);
        return previous;
    }
* 

开始的时候确实是把值放入LinkedHashMap,不管超不超过你设定的缓存容量。
*
根据 safeSizeOf方法计算 此次添加数据的容量是多少,并且加到size 里 。
*
方法执行到最后时,通过trimToSize()方法 来判断size 是否大于maxSize。

可以看到put()方法并没有太多的逻辑,重要的就是在添加过缓存对象后,调用 trimToSize()方法,来判断缓存是否已满,如果满了就要删除近期最少使用的数据3.trimToSize(int maxSize)

/**
     * 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小于最大缓存,不需要再删除缓存对象,跳出循环
                if (size <= maxSize) {
                    break;
                }
     //在缓存队列中查找最近最少使用的元素,若不存在,直接退出循环,若存在则直接在map中删除。
                Map.Entry toEvict = map.eldest();
                if (toEvict == null) {
                    break;
                }

                key = toEvict.getKey();
                value = toEvict.getValue();
                map.remove(key);
                size -= safeSizeOf(key, value);
                //回收次数+1
                evictionCount++;
            }

            entryRemoved(true, key, value, null);
        }
    }
/**
* Returns the eldest entry in the map, or {@code null} if the map is empty.
*
* Android-added.
*
* @hide
*/
public Map.Entry eldest() {
    Entry eldest = header.after;
    return eldest != header ? eldest : null;
}

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

/**
     * 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.
     * 通过key获取缓存的数据,如果通过这个方法得到的需要的元素,那么这个元素会被放在缓存队列的尾部,
     *
     */
    public final V get(K key) {
        if (key == null) {
            throw new NullPointerException("key == null");
        }

        V mapValue;
        synchronized (this) {
              //从LinkedHashMap中获取数据。
            mapValue = map.get(key);
            if (mapValue != null) {
                hitCount++;
                return mapValue;
            }
            missCount++;
        }
    /*
     * 正常情况走不到下面
     * 因为默认的 create(K key) 逻辑为null
     * 走到这里的话说明实现了自定义的create(K key) 逻辑,比如返回了一个不为空的默认值
     */
        /*
         * Attempt to create a value. This may take a long time, and the map
         * may be different when create() returns. If a conflicting value was
         * added to the map while create() was working, we leave that value in
         * the map and release the created value.
         * 译:如果通过key从缓存集合中获取不到缓存数据,就尝试使用creat(key)方法创造一个新数据。
         * create(key)默认返回的也是null,需要的时候可以重写这个方法。
         */

        V createdValue = create(key);
        if (createdValue == null) {
            return null;
        }
        //如果重写了create(key)方法,创建了新的数据,就讲新数据放入缓存中。
        synchronized (this) {
            createCount++;
            mapValue = map.put(key, createdValue);

            if (mapValue != null) {
                // There was a conflict so undo that last put
                map.put(key, mapValue);
            } else {
                size += safeSizeOf(key, createdValue);
            }
        }

        if (mapValue != null) {
            entryRemoved(false, key, createdValue, mapValue);
            return mapValue;
        } else {
            trimToSize(maxSize);
            return createdValue;
        }
    }

当调用LruCache的get()方法获取集合中的缓存对象时,就代表访问了一次该元素,将会更新队列,保持整个队列是按照访问顺序排序,这个更新过程就是在LinkedHashMap中的get()方法中完成的。总结
*
LruCache中维护了一个集合LinkedHashMap,该LinkedHashMap是以访问顺序排序的。
*
当调用put()方法时,就会在结合中添加元素,并调用trimToSize()判断缓存是否已满,如果满了就用LinkedHashMap的迭代器删除队首元素,即近期最少访问的元素。
*
当调用get()方法访问缓存对象时,就会调用LinkedHashMap的get()方法获得对应集合元素,同时会更新该元素到队尾。

面试题:LRU算法实现原理以及在项目中的应用
一个基于LinkedHashMap的LRU缓存淘汰算法,
这个缓存淘汰列表包含了一个最大的节点值,如果在列表满了之后再有额外的值添加进来,
则LRU(最近最少使用)的节点将被移除列表外
当前类是线程安全的,所有的方法都被同步了

LRUCache使用,又是LinkedHashMap使用,LRU算法就是淘汰算法,其中内置了一个LinkedHashMap来存储数据。图片加载框架Glide,其中大部分算法都是LRU算法;有内存缓存算法和磁盘缓存算法(DiskLRUCache); 当缓存的内存达到一定限度时,就会从列表中移除图片(当然Glide有活动内存和内存两个,并不是直接删除掉)。

你可能感兴趣的:(2019年)