相信大家在平常的开发中都接触过HashMap和LinkedHashMap,但对他们之间的区别可能有些人还不是很清楚-------LinkedHashMap可控制按插入顺序读取和按访问顺序读取,今天我就来说下LinkedHashMap的访问有序的特性和基于LinkedHashMap实现的LCUCache缓存对象。
所谓的访问有序就是指LinkedHashMap将近期访问的元素置后,访问越频繁的元素越往后移,前面的元素则是最久未被访问的元素,基于这一特性。我们可以用LinkedHashMap实现LCUCache缓存对象。
本次源码讲解是基于jdk1.8版本。
LinkedHashMap通过继承HashMap获得了大部分通用代码,其中就包括put方法,LinkedHashMap并没有覆写HashMap的put方法,只复写了get方法。
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node[] tab; Node p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key //如果put的key已经存在,则覆盖value并且将这个节点移到链表最后
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e); //将参数节点移到链表最后,这个方法在HashMap并没有具体实现方法,回调LinkedHashMap中的具体实现
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);//节点插入后的操作,是否删除最老的节点。这个方法在HashMap并没有具体实现方法,回调LinkedHashMap中的具体实现
return null;
}
// Callbacks to allow LinkedHashMap post-actions
void afterNodeAccess(Node p) { }
void afterNodeInsertion(boolean evict) { }
void afterNodeRemoval(Node p) { }
LinkedHashMap虽没有覆写HashMap的put方法,但是为了满足LinkedHashMap的特性,HashMap也给LinkedHash留了几个回调入口,即在put方法中调用LinkedHashMap的afterNodeInsertion和afterNodeAccess方法。
下面剖析下这俩个函数在LinkedHashMap的具体实现逻辑。
afterNodeInsertion
void afterNodeInsertion(boolean evict) { // possibly remove eldest 在往链表尾部插入新元素时,是否将首部最老元素移除
LinkedHashMap.Entry first;
if (evict && (first = head) != null && removeEldestEntry(first)) {
K key = first.key;
removeNode(hash(key), key, null, false, true);
}
}
protected boolean removeEldestEntry(Map.Entry eldest) { //默认是不移除首部最老元素,如需实现自定义的LRUCache对象,则根据需要复写该方法
return false;
}
afterNodeAccess
void afterNodeAccess(Node e) { // move node to last 将访问的节点移至链表末尾,并且修改modcount
LinkedHashMap.Entry last;
if (accessOrder && (last = tail) != e) {
LinkedHashMap.Entry p =
(LinkedHashMap.Entry)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;
}
}
通过上面的代码来理清下LinkedHashMap的put逻辑。即在添加新元素的时候,如果不存在key的映射,则默认将新的节点连接到尾部,否则替换value值并将该节点移到尾部。在完成新的节点插入后,LinkedHashMap可根据removeEldestEntry函数的返回值判断是否执行删除首部最老元素,从而将最久未被使用的元素剔除,这也是LCUCache实现的基本原理,默认是不删除。
LinkedHashMap相对于HashMap的最大不同就是get逻辑了,下面开始讲解其是如何实现按访问顺序进行迭代的。
public V get(Object key) {
Node e;
if ((e = getNode(hash(key), key)) == null)
return null;
if (accessOrder) //accessOrder时LinkedHashMap的一个成员变量,通过他控制LinkedHashMap是按插入顺序迭代还是按访问顺序迭代
afterNodeAccess(e);//如果accseeOrder为true的话,则将当前访问节点移至末尾,从而改变迭代顺序
return e.value;
}
从代码可以看出,LinkedHashMap有accessOrder控制其迭代方式,所以我们如果要求LinkedHashMap由访问顺序进行迭代的话,则需要调用
public LinkedHashMap(int initialCapacity,
float loadFactor,
boolean accessOrder) {
super(initialCapacity, loadFactor);
this.accessOrder = accessOrder;
}
构造方法实例化LinkedHashMap对象,其默认是按插入顺序进行迭代的。当开启按访问顺序迭代,我们每get一个key的时候,linkedHashMap就会将该节点移至末尾,所以链表前端都是最少最近使用对象(least currently used ,LCU),从而实现按访问顺序进行迭代。
/**
* LinkedHashMap通过设置accssOrder来判断是使用查询顺序进行迭代还是访问顺序进行迭代
* 通过继承LinkedHashMap实现LRUCache缓存类
* @author lujunfa
*
*/
class LRUCache extends LinkedHashMap{
public LRUCache(boolean accessOrder) {//true 设置缓存为访问排序,即最新访问节点都排在队列的最后,最前面的都是最久未被使用的节点
// TODO Auto-generated constructor stub
super(16,(float) 0.75,accessOrder);
}
/**
* 复写removeEldestEntry方法,实现当·达到阈值删除最久未使用的节点
*/
@Override
protected boolean removeEldestEntry(java.util.Map.Entry eldest) {
// TODO Auto-generated method stub
if(size()>5)
return true;
else
return false;
}
}
public class LRUCacheDemon {
public static void main(String[] args) {
LRUCache cache = new LRUCache(true);
cache.put("1", "lujunfa");
cache.put("2", "lujunfa2");
cache.put("3", "lujunfa3");
cache.put("4", "lujunfa4");
cache.put("5", "lujunfa5");
cache.get("3");//将3节点排到最后
Iterator iterator = cache.entrySet().iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
System.out.println("当cache中的数据容量大于5时,会丢弃最久未被使用的");
cache.put("6", "lujunfa6");//设置LRUCache的缓存大小为5,所以当达到最大容量还往缓存放数据时,则前面的部分会被删除
cache.put("7", "lujunfa7");
Iterator iterator2 = cache.entrySet().iterator();
while(iterator2.hasNext()){
System.out.println(iterator2.next());
}
}
}