`
m635674608
  • 浏览: 4935249 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

基于LinkedHashMap实现LRU缓存调度算法原理及应用

    博客分类:
  • java
 
阅读更多

在Android中实用LRU+软引用(弱引用)的方法来缓存图片,可以减少内存溢出的情况。

实现思路:

在把图片保存到LRU集合中的时候,同时保存在一个弱引用的集合之中,如果此元素被LRU算法删除,可能垃圾回收器还并没有回收,可以通过弱引用的集合获取到此引用。

 


public LinkedHashMap (int initialCapacity, float loadFactor, boolean accessOrder);

 initialCapacity   初始容量

 loadFactor    加载因子,一般是 0.75f

 accessOrder   false 基于插入顺序  true  基于访问顺序(get一个元素后,这个元素被加到最后,使用了LRU  最近最少被使用的调度算法)

 
当有新元素加入Map的时候会调用Entry的addEntry方法,会调用removeEldestEntry方法,这里就是实现LRU元素过期机制的地方,默认的情况下removeEldestEntry方法只返回false表示元素永远不过期。 
 
如 boolean accessOrder = true; 
      Map<String, String> m = new LinkedHashMap<String, String>(20, .80f,  accessOrder  );
      m.put("1", "my"));

      m.put("2", "map"));

      m.put("3", "test"));

      m.get("1");

      m.get("2");

      Log.d("tag",  m);

     若 accessOrder == true;  输出 {3=test, 1=my, 2=map}

         accessOrder == false;  输出 {1=my, 2=map,3=test}

 

LinkedHashMap已经为我们自己实现LRU算法提供了便利。 
LinkedHashMap继承了HashMap底层是通过Hash表+单向链表实现Hash算法,内部自己维护了一套元素访问顺序的列表。 
  1. /** 
  2.   * The head of the doubly linked list. 
  3.   */  
  4.  private transient Entry<K,V> header;  
  5.  .....  
  6. /** 
  7.   * LinkedHashMap entry. 
  8.   */  
  9.  private static class Entry<K,V> extends HashMap.Entry<K,V> {  
  10.      // These fields comprise the doubly linked list used for iteration.  
  11.      Entry<K,V> before, after;  


HashMap构造函数中回调了子类的init方法实现对元素初始化 
  1. void init() {  
  2.     header = new Entry<K,V>(-1nullnullnull);  
  3.     header.before = header.after = header;  
  4. }  


LinkedHashMap中有一个属性可以执行列表元素的排序算法 
  1. /** 
  2.   * The iteration ordering method for this linked hash map: <tt>true</tt> 
  3.   * for access-order, <tt>false</tt> for insertion-order. 
  4.   * 
  5.   * @serial 
  6.   */  
  7.  private final boolean accessOrder;  


注释已经写的很明白,accessOrder为true使用访问顺序排序,false使用插入顺序排序那么在哪里可以设置这个值。 
  1. /** 
  2.   * Constructs an empty <tt>LinkedHashMap</tt> instance with the 
  3.   * specified initial capacity, load factor and ordering mode. 
  4.   * 
  5.   * @param  initialCapacity the initial capacity. 
  6.   * @param  loadFactor      the load factor. 
  7.   * @param  accessOrder     the ordering mode - <tt>true</tt> for 
  8.   *         access-order, <tt>false</tt> for insertion-order. 
  9.   * @throws IllegalArgumentException if the initial capacity is negative 
  10.   *         or the load factor is nonpositive. 
  11.   */  
  12.  public LinkedHashMap(int initialCapacity,  
  13.  float loadFactor,  
  14.                       boolean accessOrder) {  
  15.      super(initialCapacity, loadFactor);  
  16.      this.accessOrder = accessOrder;  
  17.  }  

那么我们就行有访问顺序排序方式实现LRU,那么哪里LinkedHashMap是如何实现LRU的呢? 
  1.    //LinkedHashMap方法  
  2.    public V get(Object key) {  
  3.        Entry<K,V> e = (Entry<K,V>)getEntry(key);  
  4.        if (e == null)  
  5.            return null;  
  6.        e.recordAccess(this);  
  7.        return e.value;  
  8.    }  
  9.    //HashMap方法  
  10.    public V put(K key, V value) {  
  11. if (key == null)  
  12.     return putForNullKey(value);  
  13.        int hash = hash(key.hashCode());  
  14.        int i = indexFor(hash, table.length);  
  15.        for (Entry<K,V> e = table[i]; e != null; e = e.next) {  
  16.            Object k;  
  17.            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {  
  18.                V oldValue = e.value;  
  19.                e.value = value;  
  20.                e.recordAccess(this);  
  21.                return oldValue;  
  22.            }  
  23.        }  
  24.   
  25.        modCount++;  
  26.        addEntry(hash, key, value, i);  
  27.        return null;  
  28.    }  


当调用get或者put方法的时候,如果K-V已经存在,会回调Entry.recordAccess()方法 
我们再看一下LinkedHashMap的Entry实现 
  1. /** 
  2.   * This method is invoked by the superclass whenever the value 
  3.   * of a pre-existing entry is read by Map.get or modified by Map.set. 
  4.   * If the enclosing Map is access-ordered, it moves the entry 
  5.   * to the end of the list; otherwise, it does nothing.  
  6.   */  
  7.  void recordAccess(HashMap<K,V> m) {  
  8.      LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;  
  9.      if (lm.accessOrder) {  
  10.          lm.modCount++;  
  11.          remove();  
  12.          addBefore(lm.header);  
  13.      }  
  14.  }  
  15.   
  16.  /** 
  17.   * Remove this entry from the linked list. 
  18.   */  
  19.  private void remove() {  
  20.      before.after = after;  
  21.      after.before = before;  
  22.  }  
  23.   
  24.  /**                                              
  25.   * Insert this entry before the specified existing entry in the list. 
  26.   */  
  27.  private void addBefore(Entry<K,V> existingEntry) {  
  28.      after  = existingEntry;  
  29.      before = existingEntry.before;  
  30.      before.after = this;  
  31.      after.before = this;  
  32.  }  

recordAccess方法会accessOrder为true会先调用remove清楚的当前首尾元素的指向关系,之后调用addBefore方法,将当前元素加入header之前。 

当有新元素加入Map的时候会调用Entry的addEntry方法,会调用removeEldestEntry方法,这里就是实现LRU元素过期机制的地方,默认的情况下removeEldestEntry方法只返回false表示元素永远不过期。 
  1.   /** 
  2.     * This override alters behavior of superclass put method. It causes newly 
  3.     * allocated entry to get inserted at the end of the linked list and 
  4.     * removes the eldest entry if appropriate. 
  5.     */  
  6.    void addEntry(int hash, K key, V value, int bucketIndex) {  
  7.        createEntry(hash, key, value, bucketIndex);  
  8.   
  9.        // Remove eldest entry if instructed, else grow capacity if appropriate  
  10.        Entry<K,V> eldest = header.after;  
  11.        if (removeEldestEntry(eldest)) {  
  12.            removeEntryForKey(eldest.key);  
  13.        } else {  
  14.            if (size >= threshold)   
  15.                resize(2 * table.length);  
  16.        }  
  17.    }  
  18.   
  19.    /** 
  20.     * This override differs from addEntry in that it doesn't resize the 
  21.     * table or remove the eldest entry. 
  22.     */  
  23.    void createEntry(int hash, K key, V value, int bucketIndex) {  
  24.        HashMap.Entry<K,V> old = table[bucketIndex];  
  25. Entry<K,V> e = new Entry<K,V>(hash, key, value, old);  
  26.        table[bucketIndex] = e;  
  27.        e.addBefore(header);  
  28.        size++;  
  29.    }  
  30.   
  31.    protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {  
  32.        return false;  
  33.    }  


基本的原理已经介绍完了,那基于LinkedHashMap我们看一下是该如何实现呢? 
  1. public static class LRULinkedHashMap<K, V> extends LinkedHashMap<K, V> {  
  2.   
  3.         /** serialVersionUID */  
  4.         private static final long serialVersionUID = -5933045562735378538L;  
  5.   
  6.         /** 最大数据存储容量 */  
  7.         private static final int  LRU_MAX_CAPACITY     = 1024;  
  8.   
  9.         /** 存储数据容量  */  
  10.         private int               capacity;  
  11.   
  12.         /** 
  13.          * 默认构造方法 
  14.          */  
  15.         public LRULinkedHashMap() {  
  16.             super();  
  17.         }  
  18.   
  19.         /** 
  20.          * 带参数构造方法 
  21.          * @param initialCapacity   容量 
  22.          * @param loadFactor        装载因子 
  23.          * @param isLRU             是否使用lru算法,true:使用(按方案顺序排序);false:不使用(按存储顺序排序) 
  24.          */  
  25.         public LRULinkedHashMap(int initialCapacity, float loadFactor, boolean isLRU) {  
  26.             super(initialCapacity, loadFactor, true);  
  27.             capacity = LRU_MAX_CAPACITY;  
  28.         }  
  29.   
  30.         /** 
  31.          * 带参数构造方法 
  32.          * @param initialCapacity   容量 
  33.          * @param loadFactor        装载因子 
  34.          * @param isLRU             是否使用lru算法,true:使用(按方案顺序排序);false:不使用(按存储顺序排序) 
  35.          * @param lruCapacity       lru存储数据容量        
  36.          */  
  37.         public LRULinkedHashMap(int initialCapacity, float loadFactor, boolean isLRU, int lruCapacity) {  
  38.             super(initialCapacity, loadFactor, true);  
  39.             this.capacity = lruCapacity;  
  40.         }  
  41.   
  42.         /**  
  43.          * @see java.util.LinkedHashMap#removeEldestEntry(java.util.Map.Entry) 
  44.          */  
  45.         @Override  
  46.         protected boolean removeEldestEntry(Entry<K, V> eldest) {  
  47.             System.out.println(eldest.getKey() + "=" + eldest.getValue());  
  48.               
  49.             if(size() > capacity) {  
  50.                 return true;  
  51.             }  
  52.             return false;  
  53.         }  
  54.     }  


测试代码: 
  1. public static void main(String[] args) {  
  2.   
  3.     LinkedHashMap<String, String> map = new LRULinkedHashMap<String, String>(160.75f, true);  
  4.     map.put("a""a"); //a  a  
  5.     map.put("b""b"); //a  a b  
  6.     map.put("c""c"); //a  a b c  
  7.     map.put("a""a"); //   b c a       
  8.     map.put("d""d"); //b  b c a d  
  9.     map.put("a""a"); //   b c d a  
  10.     map.put("b""b"); //   c d a b       
  11.     map.put("f""f"); //c  c d a b f  
  12.     map.put("g""g"); //c  c d a b f g  
  13.   
  14.     map.get("d"); //c a b f g d  
  15.     for (Entry<String, String> entry : map.entrySet()) {  
  16.         System.out.print(entry.getValue() + ", ");  
  17.     }  
  18.     System.out.println();  
  19.   
  20.     map.get("a"); //c b f g d a  
  21.     for (Entry<String, String> entry : map.entrySet()) {  
  22.         System.out.print(entry.getValue() + ", ");  
  23.     }  
  24.     System.out.println();  
  25.   
  26.     map.get("c"); //b f g d a c  
  27.     for (Entry<String, String> entry : map.entrySet()) {  
  28.         System.out.print(entry.getValue() + ", ");  
  29.     }  
  30.     System.out.println();  
  31.   
  32.     map.get("b"); //f g d a c b  
  33.     for (Entry<String, String> entry : map.entrySet()) {  
  34.         System.out.print(entry.getValue() + ", ");  
  35.     }  
  36.     System.out.println();  
  37.   
  38.     map.put("h""h"); //f  f g d a c b h  
  39.     for (Entry<String, String> entry : map.entrySet()) {  
  40.         System.out.print(entry.getValue() + ", ");  
  41.     }  
  42.     System.out.println();  
  43. }  

 

运行结果: 
a=a 
a=a 
a=a 
b=b 
c=c 
c=c 
c, a, b, f, g, d, 
c, b, f, g, d, a, 
b, f, g, d, a, c, 
f, g, d, a, c, b, 
f=f 
f, g, d, a, c, b, h, 
分享到:
评论

相关推荐

    Java和Android的LRU缓存及实现原理

    Android提供了LRUCache类,可以方便的使用它来实现LRU算法的缓存。Java提供了LinkedHashMap,可以用该类很方便的实现LRU算法,Java的LRULinkedHashMap就是直接继承了LinkedHashMap,进行了极少的改动后就可以实现LRU...

    Java和Android的Lru缓存及其实现原理

     Android提供了LRUCache类,可以方便的使用它来实现LRU算法的缓存。Java提供了LinkedHashMap,可以用该类很方便的实现LRU算法,Java的LRULinkedHashMap是直接继承了LinkedHashMap,进行了极少的改动后可以实现LRU...

    LinkedHashMap的实现原理

    这是关于Java学习的主要针对LinkedHashMap的实现原理

    实现 LRU 算法,和 Caffeine 和 Redis 中的缓存淘汰策略.docx

    通过一个特殊的构造函数,三个参数的这种,最后一个布尔值参数表示是否要维护最近访问顺序,如果是 true 的话会维护最近访问的顺序,如果是 false 的话,只会维护插入...LinkedHashMap这种结构非常适合构造 LRU 缓存。

    leetcode跳跃-datastructure:数据结构

    基于LinkedHashMap实现LRU算法 PalindromeBaseArray 基于数组实现回文串的判断 链表练习 SingleLinkedList 实现单链表的增、删、改、查操作 LRUBaseLinkedList 基于单链表实现LRU算法 PalindromeBaseLinked 基于链表...

    JAVA工具类

    LruCacheUtils - 基于LinkedHashMap实现LRU缓存的工具类 MemcachedUtils - 基于memcached的工具类 RedisUtils - 基于redis的工具类,与redis的集群配置无缝结合 db JdbcUtils - 操作jdbc的工具类 MongodbUtils - ...

    ImageLoaderDemo图片三级缓存

    分成三级对图片进行缓存,第一级采用LinkedHashMap(LRU算法),第二季采用ConcurrentHashMap线程安全控制

    com.yangc.utils:工作中积累的工具类

    cacheEhCacheUtils - 基于ehcache的工具类LruCacheUtils - 基于LinkedHashMap实现LRU缓存的工具类MemcachedUtils - 基于memcached的工具类XMemcachedUtils - 基于memcached的工具类(使用XMemcached客户端)Redis...

    深入Java集合学习系列(四):LinkedHashMap的实现原理

    深入Java集合学习系列(四): LinkedHashMap的实现原理

    leetcode下载-LruCache:实现LRU算法的Cache类

    SDK中的LruCache类参考实现的LRU算法缓存存储类. 原理 之前分析过Lru算法的实现方式:HashMap+双向链表,参考链接: 这里主要介绍Android SDK中LruCache缓存算法的实现. 构造函数 LruCache只有一个构造函数,并且有一个...

    【Java面试+Java学习指南】 一份涵盖大部分Java程序员所需要掌握的核心知识

    ava基础 基础知识 ...Java集合详解5:深入理解LinkedHashMap和LRU缓存 Java集合详解6:TreeMap和红黑树 Java集合详解7:HashSet,TreeSet与LinkedHashSet Java集合详解8:Java集合类细节精讲 JavaWeb

    集合常见面试题

    如何用LinkedHashMap实现LRU? 如何用TreeMap实现一致性hash? ConcurrentHashMap是如何在保证并发安全的同时提高性能? ConcurrentHashMap是如何让多线程同时参与扩容? LinkedBlockingQueue、DelayQueue是如何实现...

    今天会是有Offer的一天么:面试时不要再问我LinkedHashMap了

    要注意一点的是LinkedHashMap是可以实现LRU缓存策略的,前提是你需要将LinkedHashMap中的accessorder属性设置为true。 因此你基本可以认为LinkedHashMap是LinkedList和HashMap的一个组合。 LinkedHashMap简介 ...

    尚硅谷-深入Java集合4:LinkedHashMap的实现原理.pdf

    ·基于JDK 11,将Java8、Java9、Java10、Java11新特性一网打尽 ·课程中,Eclipse和IDEA这两种企业一线开发环境都使用到了 3.技术讲解更深入、更全面: ·课程共30天,715个知识视频小节,涉及主流Java使用的...

    Java LinkedHashMap工作原理及实现

     在理解了#7 介绍的HashMap后,我们来学习LinkedHashMap的工作原理及实现。首先还是类似的,我们写一个简单的LinkedHashMap的程序:  LinkedHashMap&lt;String&gt; lmap = new LinkedHashMap();  lmap.put(语文, 1)...

    尚硅谷-深入java8的集合4:LinkedHashMap的实现原理.pdf

    ·基于JDK 11,将Java8、Java9、Java10、Java11新特性一网打尽 ·课程中,Eclipse和IDEA这两种企业一线开发环境都使用到了 3.技术讲解更深入、更全面: ·课程共30天,715个知识视频小节,涉及主流Java使用的...

    android实现缓存图片等数据

    采用LinkedHashMap自带的LRU 算法缓存数据, 可检测对象是否已被虚拟机回收,并且重新计算当前缓存大小,清除缓存中无用的键值对象(即已经被虚拟机回收但未从缓存清除的数据);  * 默认内存缓存大小为: 4 * 1024 * ...

    LinkedHashMap

    LinkedHashMap源代码,Java中Map的一种实现子类。

    leetcodelrucache-algorithm:算法学习和练习

    基于JavaLinkedHashMap实现的 LRU 算法 algorithm.consistentHashing ConsistentHash: 一致性Hash算法 algorithm.cap algorithm.subset 给一个set打印出所有子集 jdk jdk 知识 jdk.autoboxing 自动装箱拆箱 jdk....

    java LRU(Least Recently Used )详解及实例代码

    主要介绍了java LRU(Least Recently Used )详解及实例代码的相关资料,Java里面实现LRU缓存通常有两种选择,一种是使用LinkedHashMap,一种是自己设计数据结构,使用链表+HashMap,需要的朋友可以参考下

Global site tag (gtag.js) - Google Analytics