简介
LRU是Least Recently Used的缩写,即最近最少使用,常用于页面置换算法,是为虚拟页式存储管理服务的。
核心:如果数据最近被访问过,那么将来访问的几率也更高
利用LinkedHashMap实现
1.利用LinkedHashMap中的构造方法
要完成LRU, accessOrder必须为true
public LinkedHashMap(int initialCapacity,
float loadFactor,
boolean accessOrder) {
super(initialCapacity, loadFactor);
this.accessOrder = accessOrder;
}
2.LinkedHashMap中的put方法
当accessOrder为true时,调用afterNodeAccess,将元素移动到尾部
public V get(Object key) {
Node<K,V> e;
if ((e = getNode(hash(key), key)) == null)
return null;
if (accessOrder)
afterNodeAccess(e);
return e.value;
}
3.LinkedHashMap中的afterNodeAccess方法
将元素移动到尾部
void afterNodeAccess(Node<K,V> e) { // move node to last
LinkedHashMap.Entry<K,V> last;
if (accessOrder && (last = tail) != e) {
LinkedHashMap.Entry<K,V> p =
(LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after;
p.after = null;
if (b == null)
head = a;
else
b.after = a;
if (a != null)
a.before = b;
else
last = b;
if (last == null)
head = p;
else {
p.before = last;
last.after = p;
}
tail = p;
++modCount;
}
}
4.实现
// 缓存最大容量
static final int capacity = 3;
Map<String, String> map = new LinkedHashMap<String, String>(capacity, 0.75F, true){
// 如果map里面的元素个数大于了缓存最大容量,则删除顶端元素
@Override
protected boolean removeEldestEntry(Map.Entry<String, String> eldest) {
return size() > capacity;
}
};
测试
map.put("1","1");
map.put("2","2");
map.put("3","3");
map.get("1");
map.get("3");
map.put("4","4");
for(Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key:" + entry.getKey() + " value:" + entry.getValue());
// key:1 value:1
// key:3 value:3
// key:4 value:4
}