缓存淘汰算法 —— LFU-Aging(Java实现)

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();
            km.remove(k);
            this.remove(k);
        }
        V v = super.put(key, value);
        km.put(key, new HitRate(key, 1, System.nanoTime()));
        return v;
    }
 
    private K getLFUAging() {
        HitRate min = Collections.min(km.values());
        return min.key;
    }
 
    class HitRate implements Comparable<HitRate> {
        K key;
        Integer hitCount; // 命中次数
        Long atime; // 上次命中时间
 
        public HitRate(K key, Integer hitCount, Long atime) {
            this.key = key;
            this.hitCount = hitCount;
            this.atime = atime;
        }
 
        @Override
        public int compareTo(HitRate o) {
            int hr = hitCount.compareTo(o.hitCount);
            return hr != 0 ? hr : atime.compareTo(o.atime);
        }
    }
    public static void main(String[] as) throws Exception {
        LFUAgingMap<String, String> cache = new LFUAgingMap<String, String>();
        cache.put("a", "a");
        cache.put("b", "b");
        cache.put("c", "c");
 
        cache.get("a");
        cache.get("a");
 
        cache.put("d", "d");
        cache.get("d");
        cache.get("c");
        cache.put("e", "e");
 
        for (String key : cache.keySet()) {
            System.out.println(key);
        }
    }
}

 

 

https://blog.csdn.net/definite_things/article/details/45705307

 

 

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值