LFU
全称
least frequently used,最近频繁使用,先根据使用次数比较,次数少的移除,次数相同,比较时间,时间小的移除。
实现
public class MyTest {
private static final int capacity = 3;
private static Map<String,Hit> keyMap = new HashMap<String, Hit>();
public static void main(String[] args) {
MyTest myTest = new MyTest();
myTest.lfu("a");
myTest.lfu("b");
myTest.lfu("a");
myTest.lfu("d");
myTest.lfu("c");
System.out.println(Arrays.toString(keyMap.keySet().toArray()));
}
/**
* 比较使用次数,次数大的留着,次数相同比较访问时间,访问时间大的留着
*/
public void lfu(String key){
// 超过容量时,移除一个
if(keyMap.size() >= capacity){
Hit minHit = Collections.min(keyMap.values());
keyMap.remove(minHit.key);
}
Hit hit = keyMap.get(key);
// key没有,则添加
if(hit == null){
keyMap.put(key, new Hit(key, 1, System.nanoTime()));
}else{
// 当key有,则更新
hit.count = hit.count + 1;
hit.time = System.nanoTime();
keyMap.put(key, hit);
}
}
public static class Hit implements Comparable<Hit>{
public String key;
public int count;
public long time;
public Hit(String key, int count, long time){
this.key = key;
this.count = count;
this.time = time;
}
@Override
public int compareTo(Hit hit){
if(this.count > hit.count){
return 1;
}else if(this.count < hit.count){
return -1;
}else{
if(this.time > hit.time){
return 1;
}else{
return -1;
}
}
}
}
}