• LruCache


    一. LruCache基本原理

    LRU全称为Least Recently Used,即最近最少使用。由于缓存容量是有限的,当有新的数据需要加入缓存,但缓存的空闲空间不足的时候,如何移除原有的部分数据从而释放空间用来存放新的数据。

    LRU算法就是当缓存空间满了的时候,将最近最少使用的数据从缓存空间中删除以增加可用的缓存空间来缓存新数据。这个算法的内部有一个缓存列表,每当一个缓存数据被访问的时候,这个数据就会被提到列表尾部,每次都这样的话,列表的头部数据就是最近最不常使用的了,当缓存空间不足时,就会删除列表头部的缓存数据。

    二. LruCache的使用

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

    三. 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.构造方法

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

    LinkedHashMap参数介绍:

    • initialCapacity 用于初始化该 LinkedHashMap 的大小。

    • loadFactor(负载因子)这个LinkedHashMap的父类 HashMap 里的构造参数,涉及到扩容问题,比如 HashMap 的最大容量是100,那么这里设置0.75f的话,到75的时候就会扩容。

    • accessOrder,这个参数是排序模式,true表示在访问的时候进行排序( LruCache 核心工作原理就在此),false表示在插入的时才排序。

    2.添加数据 LruCache.put(K key, V value)

     1 /**
     2      * Caches {@code value} for {@code key}. The value is moved to the head of
     3      * the queue.
     4      *
     5      * @return the previous value mapped by {@code key}.
     6      */
     7     public final V put(K key, V value) {
     8         if (key == null || value == null) {
     9             throw new NullPointerException("key == null || value == null");
    10         }
    11 
    12         V previous;
    13         synchronized (this) {
    14             putCount++;
    15              //safeSizeOf(key, value)。
    16              //这个方法返回的是1,也就是将缓存的个数加1.
    17             // 当缓存的是图片的时候,这个size应该表示图片占用的内存的大小,所以应该重写里面调用的sizeOf(key, value)方法
    18             size += safeSizeOf(key, value);
    19             //向map中加入缓存对象,若缓存中已存在,返回已有的值,否则执行插入新的数据,并返回null
    20             previous = map.put(key, value);
    21             //如果已有缓存对象,则缓存大小恢复到之前
    22             if (previous != null) {
    23                 size -= safeSizeOf(key, previous);
    24             }
    25         }
    26           //entryRemoved()是个空方法,可以自行实现
    27         if (previous != null) {
    28             entryRemoved(false, key, previous, value);
    29         }
    30 
    31         trimToSize(maxSize);
    32         return previous;
    33     }
    • 开始的时候确实是把值放入LinkedHashMap,不管超不超过你设定的缓存容量。
    • 根据 safeSizeOf方法计算 此次添加数据的容量是多少,并且加到size 里 。
    • 方法执行到最后时,通过trimToSize()方法 来判断size 是否大于maxSize。

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

    2.trimToSize(int maxSize)

     1 /**
     2      * Remove the eldest entries until the total of remaining entries is at or
     3      * below the requested size.
     4      *
     5      * @param maxSize the maximum size of the cache before returning. May be -1
     6      *            to evict even 0-sized elements.
     7      */
     8     public void trimToSize(int maxSize) {
     9         while (true) {
    10             K key;
    11             V value;
    12             synchronized (this) {
    13               //如果map为空并且缓存size不等于0或者缓存size小于0,抛出异常
    14                 if (size < 0 || (map.isEmpty() && size != 0)) {
    15                     throw new IllegalStateException(getClass().getName()
    16                             + ".sizeOf() is reporting inconsistent results!");
    17                 }
    18      //如果缓存大小size小于最大缓存,不需要再删除缓存对象,跳出循环
    19                 if (size <= maxSize) {
    20                     break;
    21                 }
    22      //在缓存队列中查找最近最少使用的元素,若不存在,直接退出循环,若存在则直接在map中删除。
    23                 Map.Entry<K, V> toEvict = map.eldest();
    24                 if (toEvict == null) {
    25                     break;
    26                 }
    27 
    28                 key = toEvict.getKey();
    29                 value = toEvict.getValue();
    30                 map.remove(key);
    31                 size -= safeSizeOf(key, value);
    32                 //回收次数+1
    33                 evictionCount++;
    34             }
    35 
    36             entryRemoved(true, key, value, null);
    37         }
    38     }
    39 
    40 
    41 /**
    42  * Returns the eldest entry in the map, or {@code null} if the map is empty.
    43  *
    44  * Android-added.
    45  *
    46  * @hide
    47  */
    48 public Map.Entry<K, V> eldest() {
    49     Entry<K, V> eldest = header.after;
    50     return eldest != header ? eldest : null;
    51 }

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

    3.LruCache.get(K key)

     1  /**
     2      * Returns the value for {@code key} if it exists in the cache or can be
     3      * created by {@code #create}. If a value was returned, it is moved to the
     4      * head of the queue. This returns null if a value is not cached and cannot
     5      * be created.
     6      * 通过key获取缓存的数据,如果通过这个方法得到的需要的元素,那么这个元素会被放在缓存队列的尾部,
     7      * 
     8      */
     9     public final V get(K key) {
    10         if (key == null) {
    11             throw new NullPointerException("key == null");
    12         }
    13 
    14         V mapValue;
    15         synchronized (this) {
    16               //从LinkedHashMap中获取数据。
    17             mapValue = map.get(key);
    18             if (mapValue != null) {
    19                 hitCount++;
    20                 return mapValue;
    21             }
    22             missCount++;
    23         }
    24     /*
    25      * 正常情况走不到下面
    26      * 因为默认的 create(K key) 逻辑为null
    27      * 走到这里的话说明实现了自定义的create(K key) 逻辑,比如返回了一个不为空的默认值
    28      */
    29         /*
    30          * Attempt to create a value. This may take a long time, and the map
    31          * may be different when create() returns. If a conflicting value was
    32          * added to the map while create() was working, we leave that value in
    33          * the map and release the created value.
    34          * 译:如果通过key从缓存集合中获取不到缓存数据,就尝试使用creat(key)方法创造一个新数据。
    35          * create(key)默认返回的也是null,需要的时候可以重写这个方法。
    36          */
    37 
    38         V createdValue = create(key);
    39         if (createdValue == null) {
    40             return null;
    41         }
    42         //如果重写了create(key)方法,创建了新的数据,就讲新数据放入缓存中。
    43         synchronized (this) {
    44             createCount++;
    45             mapValue = map.put(key, createdValue);
    46 
    47             if (mapValue != null) {
    48                 // There was a conflict so undo that last put
    49                 map.put(key, mapValue);
    50             } else {
    51                 size += safeSizeOf(key, createdValue);
    52             }
    53         }
    54 
    55         if (mapValue != null) {
    56             entryRemoved(false, key, createdValue, mapValue);
    57             return mapValue;
    58         } else {
    59             trimToSize(maxSize);
    60             return createdValue;
    61         }
    62     }

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

    总结

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

    面试题:LRU算法实现原理以及在项目中的应用

    上面说到,最近最少使用将排除在列表之外,那这个列表是什么?? 通过源码得知,jdk中实现的LRU算法内部持有了一个LinkedHashMap:

     1 /**
     2  *一个基于LinkedHashMap的LRU缓存淘汰算法,
     3  * 这个缓存淘汰列表包含了一个最大的节点值,如果在列表满了之后再有额外的值添加进来,
     4  * 则LRU(最近最少使用)的节点将被移除列表外
     5  * 
     6  * 当前类是线程安全的,所有的方法都被同步了
     7  */
     8 public class LRUCache<K, V> {
     9 
    10     private static final float hashTableLoadFactor = 0.75f;
    11     private LinkedHashMap<K, V> map;
    12     private int cacheSize;
    13     
    14     //...
    15 }

    而LinkedHashMap内部节点的特性就是一个双向链表,有头结点和尾节点,有下一个指针节点和上一个指针节点;LRUCache中,主要是put() 与 get () 两个方法,LinkedHashMap是继承至HashMap,查看源码得知LinkedHashMap并没有重写父类的put方法,而是实现了其中另外一个方法,afterNodeInsertion() 接下来分析一下LinkedHashMap中的put() 方法:

     1  // 由LinkedHashMap 实现回调
     2     void afterNodeAccess(Node<K,V> p) { }
     3     void afterNodeInsertion(boolean evict) { }
     4     void afterNodeRemoval(Node<K,V> p) { }
     5 
     6 // HashMap.put()
     7  final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
     8                    boolean evict) {
     9         Node<K,V>[] tab; Node<K,V> p; int n, i;
    10         if ((tab = table) == null || (n = tab.length) == 0)
    11             n = (tab = resize()).length;
    12         if ((p = tab[i = (n - 1) & hash]) == null)
    13             tab[i] = newNode(hash, key, value, null);
    14         else {
    15             Node<K,V> e; K k;
    16             if (p.hash == hash &&
    17                 ((k = p.key) == key || (key != null && key.equals(k))))
    18                 e = p;
    19             else if (p instanceof TreeNode)
    20                 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
    21             else {
    22                 for (int binCount = 0; ; ++binCount) {
    23                     if ((e = p.next) == null) {
    24                         p.next = newNode(hash, key, value, null);
    25                         if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
    26                             treeifyBin(tab, hash);
    27                         break;
    28                     }
    29                     if (e.hash == hash &&
    30                         ((k = e.key) == key || (key != null && key.equals(k))))
    31                         break;
    32                     p = e;
    33                 }
    34             }
    35             if (e != null) { // existing mapping for key
    36                 V oldValue = e.value;
    37                 if (!onlyIfAbsent || oldValue == null)
    38                     e.value = value;
    39                 afterNodeAccess(e);
    40                 return oldValue;
    41             }
    42         }
    43         ++modCount;
    44         if (++size > threshold)
    45             resize();
    46         // 回调给LinkedHashMap ,evict为boolean
    47         afterNodeInsertion(evict);
    48         return null;
    49     }

    可以看到新增节点的方法,是由父类实现,并传递回调函数afterNodeInsertion(evict) 给LinkedHashMap实现:

    1 void afterNodeInsertion(boolean evict) { // 可能移除最老的节点
    2         LinkedHashMap.Entry<K,V> first;
    3         if (evict && (first = head) != null && removeEldestEntry(first)) {
    4             K key = first.key;
    5             removeNode(hash(key), key, null, false, true);
    6         }
    7     }

    可以看到 if 中有一个removeEldestEntry(first) 方法,该方法是给用户去实现的,该怎样去移除这个节点,最常用的是判断当前列表的长度是否大于缓存节点的长度:

     1 this.map = new LinkedHashMap<K, V>(hashTableCapacity, LRUCache.hashTableLoadFactor, true) {
     2             // (an anonymous inner class)
     3 
     4             private static final long serialVersionUID = 1;
     5 
     6             @Override
     7             protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
     8                 // 返回为true的话可能移除节点
     9                 return this.size() > LRUCache.this.cacheSize;
    10             }
    11         };

    接下来就是get() 方法了:

     1 public V get(Object key) {
     2         Node<K,V> e;
     3         if ((e = getNode(hash(key), key)) == null)
     4             return null;
     5         if (accessOrder)
     6             // 调用HashMap给LinkedHashMap的回调方法
     7             afterNodeAccess(e);
     8         return e.value;
     9     }
    10 // afterNodeAccess(e)
    11  void afterNodeAccess(Node<K,V> e) { // move node to last 将节点移到最后
    12         LinkedHashMap.Entry<K,V> last;
    13         if (accessOrder && (last = tail) != e) {
    14             LinkedHashMap.Entry<K,V> p =
    15                 (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after;
    16             p.after = null;
    17             if (b == null)
    18                 head = a;
    19             else
    20                 b.after = a;
    21             if (a != null)
    22                 a.before = b;
    23             else
    24                 last = b;
    25             if (last == null)
    26                 head = p;
    27             else {
    28                 p.before = last;
    29                 last.after = p;
    30             }
    31             tail = p;
    32             ++modCount;
    33         }
    34     }

    所以在这个方法中,就将我们上面说到的最近最常使用的节点移到最后,而最近最少使用的节点自然就排列到了前面,如果需要移除的话,就从前面删除掉了节点。

    总结

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

  • 相关阅读:
    URL中“#”
    2、Distributed Optimization
    转:增强学习(二)----- 马尔可夫决策过程MDP
    转:强化学习(Reinforcement Learning)
    强化学习学习资料
    转:A Painless Q-learning Tutorial (一个 Q-learning 算法的简明教程)
    1、通过搜索进行问题求解
    CMOS与BIOS
    转:Spring-session & redis 子域名共享session
    基于 token 的认证应用
  • 原文地址:https://www.cnblogs.com/linghu-java/p/10034284.html
Copyright © 2020-2023  润新知