- 浏览: 56636 次
- 性别:
- 来自: 杭州
最新评论
-
bibithink:
LinkedHashMap 的内部实现是 一个哈希表 + 双向 ...
基于LinkedHashMap实现LRU缓存调度算法原理及应用 -
javaboy2010:
不错,还没毕业,写出如此代码,楼主很强啊! 向楼主学习!
自己编写一个基于Velocity的MVC框架 -
lwclover:
lz的代码在多线程环境下 会出问题
基于LinkedHashMap实现LRU缓存调度算法原理及应用 -
woming66:
condeywadl 写道观爷我来顶一个 哈哈
哈哈 你来晚 ...
基于LinkedHashMap实现LRU缓存调度算法原理及应用 -
condeywadl:
观爷我来顶一个 哈哈
基于LinkedHashMap实现LRU缓存调度算法原理及应用
最近手里事情不太多,随意看了看源码,在学习缓存技术的时候,都少不了使用各种缓存调度算法(FIFO,LRU,LFU),今天总结一下LRU算法。
LinkedHashMap已经为我们自己实现LRU算法提供了便利。
LinkedHashMap继承了HashMap底层是通过Hash表+单向链表实现Hash算法,内部自己维护了一套元素访问顺序的列表。
HashMap构造函数中回调了子类的init方法实现对元素初始化
LinkedHashMap中有一个属性可以执行列表元素的排序算法
注释已经写的很明白,accessOrder为true使用访问顺序排序,false使用插入顺序排序那么在哪里可以设置这个值。
那么我们就行有访问顺序排序方式实现LRU,那么哪里LinkedHashMap是如何实现LRU的呢?
当调用get或者put方法的时候,如果K-V已经存在,会回调Entry.recordAccess()方法
我们再看一下LinkedHashMap的Entry实现
recordAccess方法会accessOrder为true会先调用remove清楚的当前首尾元素的指向关系,之后调用addBefore方法,将当前元素加入header之前。
当有新元素加入Map的时候会调用Entry的addEntry方法,会调用removeEldestEntry方法,这里就是实现LRU元素过期机制的地方,默认的情况下removeEldestEntry方法只返回false表示元素永远不过期。
基本的原理已经介绍完了,那基于LinkedHashMap我们看一下是该如何实现呢?
测试代码:
运行结果:
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,
哈哈 你来晚了~
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
观爷我来顶一个 哈哈
发表评论
-
转:用消息队列和消息应用状态表来消除分布式事务
2012-07-18 21:53 1416由于数据量的巨大,大 ... -
RRiBbit学习笔记
2012-07-17 21:42 4952RRiBbit可以作为事件总线Eventbus, 能够让组件之 ... -
安全发布原则
2012-04-18 21:48 1012public class XXX { private ... -
Java NIO Reactor模式
2011-10-11 15:57 4401package com.zzq.nio.reactor; ... -
并发控制—CAS
2011-07-07 23:55 1660public class AtomicIntegerTes ... -
压力测试JSON-RPC服务
2011-06-21 14:30 3929/** * 压力测试JSON-RPC服务 * * ... -
缓存失效算法比较
2011-06-13 20:03 1698提到缓存,有两点是必须要考虑的: 1、缓存数据和目标数据的一致 ... -
记录工作每阶段的代码质量——2011年2月20日
2011-02-20 23:45 978package com.zzq.pattern.decorat ... -
另类的Singleton模式
2010-09-03 15:15 1037package com.zzq.singleton; /** ... -
BASE64算法
2010-07-05 13:15 1173package com.zzq.base64; publ ... -
RSA算法
2010-07-05 12:01 1431package com.zzq.rsa; import ... -
自己编写一个基于Velocity的MVC框架
2010-06-02 17:28 3699公司留了作业(还有一个月毕业),让预习Velocity,在家呆 ... -
我的各种主键生成策略类
2010-05-20 13:00 1661package com.generate; impo ... -
我的日志模型
2010-05-20 12:37 1164package com.zzq.logging; / ... -
Java模板引擎——Velocity应用实例(原创)
2010-02-10 21:18 2435对于b/s架构的项目而言,表示层呈现页面技术大多数选用jsp, ...
相关推荐
Android提供了LRUCache类,可以方便的使用它来实现LRU算法的缓存。Java提供了LinkedHashMap,可以用该类很方便的实现LRU算法,Java的LRULinkedHashMap就是直接继承了LinkedHashMap,进行了极少的改动后就可以实现LRU...
Android提供了LRUCache类,可以方便的使用它来实现LRU算法的缓存。Java提供了LinkedHashMap,可以用该类很方便的实现LRU算法,Java的LRULinkedHashMap是直接继承了LinkedHashMap,进行了极少的改动后可以实现LRU...
这是关于Java学习的主要针对LinkedHashMap的实现原理
通过一个特殊的构造函数,三个参数的这种,最后一个布尔值参数表示是否要维护最近访问顺序,如果是 true 的话会维护最近访问的顺序,如果是 false 的话,只会维护插入...LinkedHashMap这种结构非常适合构造 LRU 缓存。
基于LinkedHashMap实现LRU算法 PalindromeBaseArray 基于数组实现回文串的判断 链表练习 SingleLinkedList 实现单链表的增、删、改、查操作 LRUBaseLinkedList 基于单链表实现LRU算法 PalindromeBaseLinked 基于链表...
LruCacheUtils - 基于LinkedHashMap实现LRU缓存的工具类 MemcachedUtils - 基于memcached的工具类 RedisUtils - 基于redis的工具类,与redis的集群配置无缝结合 db JdbcUtils - 操作jdbc的工具类 MongodbUtils - ...
分成三级对图片进行缓存,第一级采用LinkedHashMap(LRU算法),第二季采用ConcurrentHashMap线程安全控制
cacheEhCacheUtils - 基于ehcache的工具类LruCacheUtils - 基于LinkedHashMap实现LRU缓存的工具类MemcachedUtils - 基于memcached的工具类XMemcachedUtils - 基于memcached的工具类(使用XMemcached客户端)Redis...
深入Java集合学习系列(四): LinkedHashMap的实现原理
SDK中的LruCache类参考实现的LRU算法缓存存储类. 原理 之前分析过Lru算法的实现方式:HashMap+双向链表,参考链接: 这里主要介绍Android SDK中LruCache缓存算法的实现. 构造函数 LruCache只有一个构造函数,并且有一个...
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是如何实现...
要注意一点的是LinkedHashMap是可以实现LRU缓存策略的,前提是你需要将LinkedHashMap中的accessorder属性设置为true。 因此你基本可以认为LinkedHashMap是LinkedList和HashMap的一个组合。 LinkedHashMap简介 ...
·基于JDK 11,将Java8、Java9、Java10、Java11新特性一网打尽 ·课程中,Eclipse和IDEA这两种企业一线开发环境都使用到了 3.技术讲解更深入、更全面: ·课程共30天,715个知识视频小节,涉及主流Java使用的...
在理解了#7 介绍的HashMap后,我们来学习LinkedHashMap的工作原理及实现。首先还是类似的,我们写一个简单的LinkedHashMap的程序: LinkedHashMap<String> lmap = new LinkedHashMap(); lmap.put(语文, 1)...
·基于JDK 11,将Java8、Java9、Java10、Java11新特性一网打尽 ·课程中,Eclipse和IDEA这两种企业一线开发环境都使用到了 3.技术讲解更深入、更全面: ·课程共30天,715个知识视频小节,涉及主流Java使用的...
采用LinkedHashMap自带的LRU 算法缓存数据, 可检测对象是否已被虚拟机回收,并且重新计算当前缓存大小,清除缓存中无用的键值对象(即已经被虚拟机回收但未从缓存清除的数据); * 默认内存缓存大小为: 4 * 1024 * ...
LinkedHashMap源代码,Java中Map的一种实现子类。
基于JavaLinkedHashMap实现的 LRU 算法 algorithm.consistentHashing ConsistentHash: 一致性Hash算法 algorithm.cap algorithm.subset 给一个set打印出所有子集 jdk jdk 知识 jdk.autoboxing 自动装箱拆箱 jdk....
主要介绍了java LRU(Least Recently Used )详解及实例代码的相关资料,Java里面实现LRU缓存通常有两种选择,一种是使用LinkedHashMap,一种是自己设计数据结构,使用链表+HashMap,需要的朋友可以参考下