LRU 是 Last Recently Used 的缩写,即最近最少使用,是一种常用的置换算法,选择最近最久未使用的数据予以淘汰。
Java 中的 LinkedHashMap 就是典型的一个 LRU 缓存系统。
// 10 是初始大小,0.75 是装载因子,true 是表示按照访问时间排序
HashMap<Integer, Integer> m = new LinkedHashMap<>(10, 0.75f, true);
m.put(3, 11);
m.put(1, 12);
m.put(5, 23);
m.put(2, 22);
for (Map.Entry e : m.entrySet()) {
System.out.println(e.getKey()); // 打印 3, 1, 5, 2
}
m.put(3, 26);
m.get(5);
for (Map.Entry e : m.entrySet()) {
System.out.println(e.getKey()); // 1, 2, 3, 5
}
这里一开始,插入之后在内存中组织为 3,1,5,2 的双向链表结构,然后插入 3,将会更新 3 的值,并将3移动到链表最尾,最后一次访问的key是 5,所以最终打印为 1,2,3,5。