LRU介绍
lru(latest recently used)最近最少使用,在缓存中可以使用LRU算法移除最近最少使用的
自定义lru算法
在java中LinkedHashMap已经实现了LRU算法,在使用时只需要继承此类,然后重写
removeEldestEntry
方法即可
public class MyLRU<K, V> extends LinkedHashMap<K, V> {
private int cacheCount;
public MyLRU(int initialCapacity) {
//必须指定accessOrder为true,true代表会重新排序,刚被访问的元素会被放到尾部,false则按照插入顺序排序
super(initialCapacity, .75f, true);
this.cacheCount = initialCapacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
//当集合中实际数量超过最大缓存,就移除最老的元素
return size() > cacheCount;
}
}