Java实现,用HashMap保存关系{key值 : 命中次数与上次命中时间},当需要淘汰某个key值时,调用map.remove(key)。
import java.util.*;
public class LFUAgingMap<K, V> extends HashMap<K, V> {
private static final int DEFAULT_MAX_SIZE = 3;
private int maxSize = DEFAULT_MAX_SIZE;
Map<K, HitRate> km = new HashMap<K, HitRate>();
public LFUAgingMap() {
this(DEFAULT_MAX_SIZE);
}
public LFUAgingMap(int maxSize) {
super(maxSize);
this.maxSize = maxSize;
}
@Override
public V get(Object key) {
V v = super.get(key);
if (v != null) {
HitRate hitRate = km.get(key);
hitRate.hitCount += 1;
hitRate.atime = System.nanoTime();
}
return v;
}
@Override
public V put(K key, V value) {
while (km.size() >= maxSize) {
K k = getLFUAging();