欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LinkedHashMap 最远未被使用丢弃缓存算法Least Recently used

程序员文章站 2022-07-10 19:18:22
...
直接贴代码

类:Test
类: LeastRecentlyUsedLinkedHashMap<K,V>


import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class Test {
public static void main(String[] args) {
/**
* LinkedHashMap 实现了Least Recently used 最远未被使用丢弃缓存算法
* :在固定大小的LinkedHashMap中如果容量大于了 size() 将丢弃最远时间未被使用的key value 是一种缓存算法
*/

LeastRecentlyUsedLinkedHashMap<String, String> lruMap = new
LeastRecentlyUsedLinkedHashMap<String, String>(5);
lruMap.put("1", "a");
lruMap.put("2", "ab");
lruMap.put("3", "abc");
lruMap.put("4", "abcd");
lruMap.put("5", "abcde");
lruMap.put("6", "abcdef");
lruMap.put("7", "abcdefg");

printMapContent(lruMap);

System.out.println("\n");
lruMap.get("3");
printMapContent(lruMap);

System.out.println("\n");
lruMap.put("8", "xxxxxx");
printMapContent(lruMap);

}

/**
* map循环
* @param lruMap
*/
public static void printMapContent(LeastRecentlyUsedLinkedHashMap lruMap){

Set<Map.Entry<String,String>>  entrySet = lruMap.entrySet();

Iterator iter = entrySet.iterator();

Map.Entry<String,String> entry = null;

while(iter.hasNext()){
entry = (Entry<String, String>) iter.next();
System.out.println("key: " + entry.getKey()+"  value: " +entry.getValue());
}
}
}



LRU算法实现类:


public class LeastRecentlyUsedLinkedHashMap<K,V> extends LinkedHashMap<K,V> {

/**
*
*/
private static final long serialVersionUID = 1L;

/*指定map规定缓存容器长度*/
private int capacity;

LeastRecentlyUsedLinkedHashMap(int capacity){
super(capacity,0.75f,true);
this.capacity = capacity;
}


protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
return size()> capacity;
}

}