栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java实现LRU缓存淘汰算法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java实现LRU缓存淘汰算法

LRU算法:最近最少使用淘汰算法(Least Recently Used)。LRU是淘汰最长时间没有被使用的缓存(即使该缓存被访问的次数最多)。

代码如下:

import java.util.*;

public class LRUCache {

    int cap;//最大缓存的数量
    Map values;//缓存
    Set position;//缓存的key,按照存入的顺序存储

    public LRUCache(int cap) {
        this.cap = cap;
        values = new HashMap<>(cap);
        position = new linkedHashSet<>(cap);
    }

    
    public String get(String key) {
        String value = null;
        if (values.containsKey(key)) {
            value = values.get(key);
            position.remove(key);
            position.add(key);
        }
        return value;
    }

    
    public void put(String key, String value) {
        if (position.size() == cap) {
            //若达到缓存上限则将距今最久的缓存删除
            String firstKey = position.iterator().next();
            position.remove(firstKey);
            values.remove(firstKey);
        }
        position.add(key);
        values.put(key, value);
    }

    public Map getValues() {
        return values;
    }

    public Set getPosition() {
        return position;
    }
}

测试:

        LRUCache lruCache = new LRUCache(4);
        lruCache.put("a","a");
        lruCache.put("b","b");
        lruCache.put("c","c");
        lruCache.put("d","d");
        System.out.println("position:"+lruCache.getPosition());
        System.out.println("values:"+lruCache.getValues());

        //a将被淘汰
        lruCache.put("e","e");
        System.out.println("position:"+lruCache.getPosition());
        System.out.println("values:"+lruCache.getValues());

输出:

position:[a, b, c, d]
values:{a=a, b=b, c=c, d=d}
position:[b, c, d, e]
values:{b=b, c=c, d=d, e=e}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/358365.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号