`
woming66
  • 浏览: 57547 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

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

阅读更多
最近手里事情不太多,随意看了看源码,在学习缓存技术的时候,都少不了使用各种缓存调度算法(FIFO,LRU,LFU),今天总结一下LRU算法。
LinkedHashMap已经为我们自己实现LRU算法提供了便利。
LinkedHashMap继承了HashMap底层是通过Hash表+单向链表实现Hash算法,内部自己维护了一套元素访问顺序的列表。
   /**
     * The head of the doubly linked list.
     */
    private transient Entry<K,V> header;
    .....
   /**
     * LinkedHashMap entry.
     */
    private static class Entry<K,V> extends HashMap.Entry<K,V> {
        // These fields comprise the doubly linked list used for iteration.
        Entry<K,V> before, after;


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


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


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

那么我们就行有访问顺序排序方式实现LRU,那么哪里LinkedHashMap是如何实现LRU的呢?
    //LinkedHashMap方法
    public V get(Object key) {
        Entry<K,V> e = (Entry<K,V>)getEntry(key);
        if (e == null)
            return null;
        e.recordAccess(this);
        return e.value;
    }
    //HashMap方法
    public V put(K key, V value) {
	if (key == null)
	    return putForNullKey(value);
        int hash = hash(key.hashCode());
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }


当调用get或者put方法的时候,如果K-V已经存在,会回调Entry.recordAccess()方法
我们再看一下LinkedHashMap的Entry实现
       /**
         * 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);
            }
        }

        /**
         * Remove this entry from the linked list.
         */
        private void remove() {
            before.after = after;
            after.before = before;
        }

        /**                                             
         * Insert this entry before the specified existing entry in the list.
         */
        private void addBefore(Entry<K,V> existingEntry) {
            after  = existingEntry;
            before = existingEntry.before;
            before.after = this;
            after.before = this;
        }

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

当有新元素加入Map的时候会调用Entry的addEntry方法,会调用removeEldestEntry方法,这里就是实现LRU元素过期机制的地方,默认的情况下removeEldestEntry方法只返回false表示元素永远不过期。
   /**
     * This override alters behavior of superclass put method. It causes newly
     * allocated entry to get inserted at the end of the linked list and
     * removes the eldest entry if appropriate.
     */
    void addEntry(int hash, K key, V value, int bucketIndex) {
        createEntry(hash, key, value, bucketIndex);

        // Remove eldest entry if instructed, else grow capacity if appropriate
        Entry<K,V> eldest = header.after;
        if (removeEldestEntry(eldest)) {
            removeEntryForKey(eldest.key);
        } else {
            if (size >= threshold) 
                resize(2 * table.length);
        }
    }

    /**
     * This override differs from addEntry in that it doesn't resize the
     * table or remove the eldest entry.
     */
    void createEntry(int hash, K key, V value, int bucketIndex) {
        HashMap.Entry<K,V> old = table[bucketIndex];
	Entry<K,V> e = new Entry<K,V>(hash, key, value, old);
        table[bucketIndex] = e;
        e.addBefore(header);
        size++;
    }

    protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
        return false;
    }


基本的原理已经介绍完了,那基于LinkedHashMap我们看一下是该如何实现呢?
public static class LRULinkedHashMap<K, V> extends LinkedHashMap<K, V> {

        /** serialVersionUID */
        private static final long serialVersionUID = -5933045562735378538L;

        /** 最大数据存储容量 */
        private static final int  LRU_MAX_CAPACITY     = 1024;

        /** 存储数据容量  */
        private int               capacity;

        /**
         * 默认构造方法
         */
        public LRULinkedHashMap() {
            super();
        }

        /**
         * 带参数构造方法
         * @param initialCapacity   容量
         * @param loadFactor        装载因子
         * @param isLRU             是否使用lru算法,true:使用(按方案顺序排序);false:不使用(按存储顺序排序)
         */
        public LRULinkedHashMap(int initialCapacity, float loadFactor, boolean isLRU) {
            super(initialCapacity, loadFactor, true);
            capacity = LRU_MAX_CAPACITY;
        }

        /**
         * 带参数构造方法
         * @param initialCapacity   容量
         * @param loadFactor        装载因子
         * @param isLRU             是否使用lru算法,true:使用(按方案顺序排序);false:不使用(按存储顺序排序)
         * @param lruCapacity       lru存储数据容量       
         */
        public LRULinkedHashMap(int initialCapacity, float loadFactor, boolean isLRU, int lruCapacity) {
            super(initialCapacity, loadFactor, true);
            this.capacity = lruCapacity;
        }

        /** 
         * @see java.util.LinkedHashMap#removeEldestEntry(java.util.Map.Entry)
         */
        @Override
        protected boolean removeEldestEntry(Entry<K, V> eldest) {
            System.out.println(eldest.getKey() + "=" + eldest.getValue());
            
            if(size() > capacity) {
                return true;
            }
            return false;
        }
    }


测试代码:
    public static void main(String[] args) {

        LinkedHashMap<String, String> map = new LRULinkedHashMap<String, String>(16, 0.75f, true);
        map.put("a", "a"); //a  a
        map.put("b", "b"); //a  a b
        map.put("c", "c"); //a  a b c
        map.put("a", "a"); //   b c a     
        map.put("d", "d"); //b  b c a d
        map.put("a", "a"); //   b c d a
        map.put("b", "b"); //   c d a b     
        map.put("f", "f"); //c  c d a b f
        map.put("g", "g"); //c  c d a b f g

        map.get("d"); //c a b f g d
        for (Entry<String, String> entry : map.entrySet()) {
            System.out.print(entry.getValue() + ", ");
        }
        System.out.println();

        map.get("a"); //c b f g d a
        for (Entry<String, String> entry : map.entrySet()) {
            System.out.print(entry.getValue() + ", ");
        }
        System.out.println();

        map.get("c"); //b f g d a c
        for (Entry<String, String> entry : map.entrySet()) {
            System.out.print(entry.getValue() + ", ");
        }
        System.out.println();

        map.get("b"); //f g d a c b
        for (Entry<String, String> entry : map.entrySet()) {
            System.out.print(entry.getValue() + ", ");
        }
        System.out.println();

        map.put("h", "h"); //f  f g d a c b h
        for (Entry<String, String> entry : map.entrySet()) {
            System.out.print(entry.getValue() + ", ");
        }
        System.out.println();
    }


运行结果:
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,
分享到:
评论
4 楼 bibithink 2016-01-04  
LinkedHashMap 的内部实现是 一个哈希表 + 双向链表 吧?
3 楼 lwclover 2012-12-23  
lz的代码在多线程环境下 会出问题
2 楼 woming66 2011-11-30  
condeywadl 写道
观爷我来顶一个 哈哈

哈哈 你来晚了~
1 楼 condeywadl 2011-11-30  
观爷我来顶一个 哈哈

相关推荐

    详解Java实现LRU缓存

    Java 实现 LRU 缓存有多种方法,本文将介绍使用 LinkedHashMap 实现 LRU 缓存的方法。 LRU 缓存原理 LRU 缓存的原理很简单,就是缓存一定量的数据,当超过设定的阈值时就把一些过期的数据删除掉。例如,我们缓存 ...

    Java实现LRU算法.zip

    在实际应用中,LRU算法不仅可以用于操作系统中的页面替换,还可以应用于数据库查询缓存、编程语言的内存管理(如Java的SoftReference和WeakReference)以及Web服务器的静态资源缓存等场景。 总的来说,Java实现LRU...

    Java实现LRU缓存的实例详解

    可以使用LinkedHashMap实现LRU缓存,通过重写removeEldestEntry方法,实现LRU缓存的效果。 3. LinkedHashMap的实现原理 LinkedHashMap是一个双向链表,加上HashTable的实现,能够记录存入其中的数据的顺序,并能按...

    LRU算法LRU算法LRU算法LRU算法

    在缓存或者数据库管理系统中,LRU算法被广泛应用,因为它的实现简单且效果良好。 LRU算法的核心思想是:当内存满时,最近最少使用的数据会被优先淘汰。也就是说,如果一个数据最近被访问过,那么它在未来被访问的...

    实现了LRU算法的缓存

    LRU缓存通常基于哈希表和双向链表实现。哈希表用于快速查找,而双向链表则用来维护元素的顺序性,以便于执行删除和插入操作。在Java中,`HashMap`可以作为哈希表,而自定义的双向链表结构或者使用`LinkedList`稍加...

    LRU_缓存策略_LRU_缓存.zip

    在这个压缩包文件“LRU_缓存策略_LRU_缓存_源码.zip”中,我们预计会找到实现LRU缓存策略的源代码,这对于理解其工作原理和应用非常有帮助。 LRU缓存策略的核心思想是:当缓存满时,优先淘汰最近最少使用的数据。这...

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

    尽管 `LinkedHashMap` 提供了便利的 LRU 实现,但在某些面试场景下,面试官可能期望候选人能够自己实现 LRU 算法,以更好地理解其工作原理。基础的 LRU 实现通常需要以下步骤: 1. 使用一个双向链表来存储数据项,...

    LRU算法 java实现

    LRU(Least Recently Used)算法是一种常用的页面替换策略,用于管理有限的...在实际应用中,LRU算法广泛应用于数据库的缓存系统、操作系统内存管理和编程语言的内置缓存机制(如Java的`java.util.LinkedHashMap`)。

    Lru缓存代码

    5. **应用场景**:LRU缓存适用于需要快速响应但又受限于内存大小的场景,例如数据库的查询缓存、操作系统的页面替换算法,以及编程语言如Java和Python的内置映射类(如Java的`LinkedHashMap`和Python的`dict`)。...

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

    Android提供了一个名为`LRUCache`的类,它是专门为Android应用设计的LRU缓存实现。`LRUCache`内部使用了`LinkedHashMap`来存储数据,并实现了缓存大小限制以及LRU淘汰机制。当你添加新的元素到`LRUCache`时,如果...

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

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

    LRU页面置换算法(Java)

    在Java中实现LRU页面置换算法,通常会用到数据结构如HashMap或LinkedHashMap,因为它们能够提供快速的查找和按照访问顺序排序的功能。HashMap提供了O(1)的时间复杂度进行查找,而LinkedHashMap则在HashMap的基础上...

    Android图片缓存之Lru算法(二)

    DiskLruCache提供了一种在磁盘上实现LRU缓存的方法,其工作原理与LruCache类似,但数据存储在文件系统而不是内存中。使用DiskLruCache可以避免内存限制,允许更大容量的缓存。 总的来说,Android中的图片缓存通过...

    Lru算法缓存解决图片OOM

    首先,我们需要创建一个基于LRU算法的缓存类。这个类通常继承自Android的`BaseCache`或者自定义一个Map结构,如`LinkedHashMap`,因为`LinkedHashMap`已经实现了LRU特性,它维护了一个双向链表,可以按照插入或访问...

    LRU.rar_LRU_lru 算法_lru算法

    在编程语言中,LRU缓存的实现通常会用到数据结构如Java的`LinkedHashMap`,Python的`collections.OrderedDict`等,它们能方便地实现按访问顺序更新的数据结构。 LRU算法的优点在于其简单性和高效性,它能在大多数...

    LRU算法实现1

    LRU(Least Recently Used)算法是一种常用的页面替换算法,用于决定在内存有限的情况下,当缓存满时应淘汰哪个数据。LRU的核心思想是:最近最少使用的数据在将来被使用的可能性最小,因此应该优先被淘汰。在Java中...

    LRU算法四种实现方式介绍.docx

    LRU 算法四种实现方式介绍 LRU 算法全称是 Least Recently Used,即最近最久未使用的意思。LRU 算法的设计原则是:...LRU 算法是一种高效的缓存算法,但需要根据实际情况选择合适的实现方式,并注意可能存在的问题。

    LRU算法--utils工具包

    LRU(Least Recently Used)算法是一种常见的缓存淘汰策略,其基本思想是“最近最少使用的数据优先被淘汰”。...通过对这三个文件的深入研究,我们可以更好地理解LRU缓存的工作原理以及如何在实际项目中应用和测试它。

Global site tag (gtag.js) - Google Analytics