LFU

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;
                }
            }
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值