4、利用数组实现LRU 缓存淘汰策略

常见的策略有三种:先进先出策略 FIFO(First In,First Out)、最少使用策略 LFU(Least Frequently Used)、最近最少使用策略 LRU(Least Recently Used)。
  • 使用链表实现LRU算法的方式很多,现在用数组也实现一下,话不多说上代码:
public class LRU {
    private static String[] lruArray = new String[10];//缓存最大容量为10
    private static String[] copyArray = new String[10];//数组元素变更时,用于数据相互拷贝
    private static HashMap<String, Integer> hashMap = new HashMap<>();
    public static void main(String[] args) throws InterruptedException {
        for(int i = 0; i < 100; i++) {
        	//取随机数
            String str = "str" + Math.round(Math.random()*20);
            //每秒调用方法打印一次
            TimeUnit.SECONDS.sleep(1);
            LRUArithmetic(str);
        }

    }
    public static void LRUArithmetic(String str) {
         //如果缓存中已有
         if(hashMap.containsKey(str)) {
             //如果str不是第一位,就重排序
             if(hashMap.get(str) > 0) {
                 int pos = hashMap.get(str);
                 //把str放在第一位
                 copyArray[0] = str;
                 //实现两个数组数据的移动
                 for(int i = 1;i <= pos; i++) {
                     copyArray[i] = lruArray[i-1];
                 }
                 for(int i = pos + 1; i < 10; i++) {
                     copyArray[i] = lruArray[i];
                 }
                //现在copyArray存放的就是新的数据,现在进行数据移动
                 for(int i = 0; i < copyArray.length; i++) {
                     lruArray[i] = copyArray[i];
                     hashMap.put(lruArray[i], i);
                 }
                 copyArray = new String[10];
             }
         } else {
             //数组中不存在,就把str放在头部,其他元素挨个后移
             copyArray[0] = str;
             hashMap.put(str, 0);
             if(!StringUtils.isEmpty(lruArray[9])) {
                 hashMap.remove(lruArray[9]);
             }
             for(int i = 1; i < copyArray.length; i++) {
                copyArray[i] = lruArray[i-1];
             }
             //现在copyArray存放的就是新的数据,现在进行数据移动
             for(int i = 0; i < copyArray.length; i++) {
                 lruArray[i] = copyArray[i];
                 hashMap.put(lruArray[i], i);
             }
             copyArray = new String[10];
         }
         //打印输出一下数组内的数据
        for(int i = 0; i < lruArray.length; i++) {
            System.out.print(lruArray[i] + ",");
        }
        System.out.println("--------------------分隔符---------------------");
    }
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值