当前位置: 首页 > news >正文

Java失效算法与应用(FIFO、LRU、LFU)

文章目录

  • 一、什么是失效算法
  • 二、先来先淘汰(FIFO)
    • 1、FIFO概述
    • 2、Java实现FIFO
    • 3、FIFO特点
  • 三、最久未用淘汰(LRU)
    • 1、LRU概述
    • 2、Java实现LRU
  • 四、最近最少使用(LFU)
    • 1、LFU概述
    • 2、Java实现LFU
  • 五、应用案例

一、什么是失效算法

失效算法常见于缓存系统中。因为缓存往往占据大量内存,而内存空间是相对昂贵,且空间有限的,那么针对一部分值,就要依据相应的算法进行失效或移除操作。

二、先来先淘汰(FIFO)

1、FIFO概述

First In First Out,先来先淘汰。这种算法在每一次新数据插入时,如果队列已满,则将最早插入的数据移除

2、Java实现FIFO

可以方便的借助LinkedList来实现。

public class FIFO {LinkedList<Integer> fifo = new LinkedList<Integer>();int size = 3;//添加元素public void add(int i){fifo.addFirst(i);if (fifo.size() > size){fifo.removeLast();}print();}//缓存命中public void read(int i){Iterator<Integer> iterator = fifo.iterator();while (iterator.hasNext()){int j = iterator.next();if (i == j){System.out.println("find it!");print();return ;}}System.out.println("not found!");print();}//打印缓存public void print(){System.out.println(this.fifo);}//测试public static void main(String[] args) {FIFO fifo = new FIFO();System.out.println("add 1-3:");fifo.add(1);fifo.add(2);fifo.add(3);System.out.println("add 4:");fifo.add(4);System.out.println("read 2:");fifo.read(2);System.out.println("read 100:");fifo.read(100);System.out.println("add 5:");fifo.add(5);}
}

结果:
add 1-3:
[1]
[2, 1]
[3, 2, 1]
add 4:
[4, 3, 2]
read 2:
find it!
[4, 3, 2]
read 100:
not found!
[4, 3, 2]
add 5:
[5, 4, 3]
Process finished with exit code 0

3、FIFO特点

我们发现,FIFO实现非常简单,不管元素的使用情况,哪怕有些数据会被频繁用到,时间最久也会被踢掉(不太理性)。

三、最久未用淘汰(LRU)

1、LRU概述

LRU全称是Least Recently Used,即淘汰最后一次使用时间最久远的数值。FIFO非常的粗暴,不管有没有用到,直接踢掉时间久的元素。而LRU认为,最近频繁使用过的数据,将来也很大程度上会被频繁用到,故而淘汰那些懒惰的数据。

2、Java实现LRU

LinkedHashMap,数组,链表均可实现LRU,下面仍然以链表为例:新加入的数据放在头部,最近访问的,也移到头部,空间满时,将尾部元素删除。

public class LRU {LinkedList<Integer> lru = new LinkedList<Integer>();int size = 3;//添加元素public void add(int i){lru.addFirst(i);if (lru.size() > size){lru.removeLast(); // 删除尾部元素}print();}//缓存命中public void read(int i){Iterator<Integer> iterator = lru.iterator();int index = 0;while (iterator.hasNext()){int j = iterator.next();if (i == j){System.out.println("find it!");// 被访问的元素移到头部lru.remove(index);lru.addFirst(j);print();return ;}index++;}System.out.println("not found!");print();}//打印缓存public void print(){System.out.println(this.lru);}//测试public static void main(String[] args) {LRU lru = new LRU();System.out.println("add 1-3:");lru.add(1);lru.add(2);lru.add(3);System.out.println("add 4:");lru.add(4);System.out.println("read 2:");lru.read(2);System.out.println("read 100:");lru.read(100);System.out.println("add 5:");lru.add(5);}
}

结果:
add 1-3:
[1]
[2, 1]
[3, 2, 1]
add 4:
[4, 3, 2]
read 2:
find it!
[2, 4, 3]
read 100:
not found!
[2, 4, 3]
add 5:
[5, 2, 4]

四、最近最少使用(LFU)

1、LFU概述

Least Frequently Used,即最近最少使用。它要淘汰的是最近一段时间内,使用次数最少的值。可以认为比LRU多了一重判断。LFU需要时间和次数两个维度的参考指标。

需要注意的是,两个维度就可能涉及到同一时间段内,访问次数相同的情况,就必须内置一个计数器和一个队列,计数器算数,队列放置相同计数时的访问时间。

2、Java实现LFU

public class Dto implements Comparable<Dto> {private Integer key;private int count;private long lastTime;public Dto(Integer key, int count, long lastTime) {this.key = key;this.count = count;this.lastTime = lastTime;}@Overridepublic int compareTo(Dto o) {int compare = Integer.compare(this.count, o.count);return compare == 0 ? Long.compare(this.lastTime, o.lastTime) : compare;}@Overridepublic String toString() {return String.format("[key=%s,count=%s,lastTime=%s]",key,count,lastTime);}public Integer getKey() {return key;}public void setKey(Integer key) {this.key = key;}public int getCount() {return count;}public void setCount(int count) {this.count = count;}public long getLastTime() {return lastTime;}public void setLastTime(long lastTime) {this.lastTime = lastTime;}
}
public class LFU {private final int size = 3;private Map<Integer,Integer> cache = new HashMap<>();private Map<Integer, Dto> count = new HashMap<>();//投放public void put(Integer key, Integer value) {Integer v = cache.get(key);if (v == null) {if (cache.size() == size) {removeElement();}count.put(key, new Dto(key, 1, System.currentTimeMillis()));} else {addCount(key);}cache.put(key, value);}//读取public Integer get(Integer key) {Integer value = cache.get(key);if (value != null) {addCount(key);return value;}return null;}//淘汰元素private void removeElement() {Dto dto  = Collections.min(count.values());cache.remove(dto.getKey());count.remove(dto.getKey());}//更新计数器private void addCount(Integer key) {Dto Dto = count.get(key);Dto.setCount(Dto.getCount()+1);Dto.setLastTime(System.currentTimeMillis());}//打印缓存结构和计数器结构private void print(){System.out.println("cache="+cache);System.out.println("count="+count);}public static void main(String[] args) {LFU lfu = new LFU();//前3个容量没满,1,2,3均加入System.out.println("add 1-3:");lfu.put(1, 1);lfu.put(2, 2);lfu.put(3, 3);lfu.print();//1,2有访问,3没有,加入4,淘汰3System.out.println("read 1,2");lfu.get(1);lfu.get(2);lfu.print();System.out.println("add 4:");lfu.put(4, 4);lfu.print();//2=3次,1,4=2次,但是4加入较晚,再加入5时淘汰1System.out.println("read 2,4");lfu.get(2);lfu.get(4);lfu.print();System.out.println("add 5:");lfu.put(5, 5);lfu.print();}
}

五、应用案例

redis属于缓存失效的典型应用场景,常见策略如下:

noeviction: 不删除策略, 达到最大内存限制时, 如果需要更多内存, 直接返回错误信息( 比较危险)。
allkeys-lru:对所有key,优先删除最近最少使用的 key (LRU)。
allkeys-random: 对所有key, 随机删除一部分(听起来毫无道理)。
volatile-lru:只限于设置了 expire 的key,优先删除最近最少使用的key (LRU)。
volatile-random:只限于设置了 expire 的key,随机删除一部分。
volatile-ttl:只限于设置了 expire 的key,优先删除剩余时间(TTL) 短的key。

http://www.lryc.cn/news/106628.html

相关文章:

  • Go语音介绍
  • Vue2与Vue3响应式原理
  • flask中写一个基础的sqlHelper类
  • opencv的Mask操作,选择图片中感兴趣的区域
  • 一次有趣的Webshell分析经历
  • 【NLP概念源和流】 05-引进LSTM网络(第 5/20 部分)
  • Vue没有node_modules怎么办
  • 企业级高负载web服务器-Tomcat小项目
  • 《golang设计模式》第一部分·创建型模式-03-建造者模式(Builder)
  • git 忽略掉不需要的文件
  • 摄像机sd卡格式化怎么恢复数据?简单五步轻松解决
  • 1-4 AUTOSAR方法论--开发流程
  • Win10查询硬盘序列号
  • 减少错误和重复工作:PDM系统的智能排错功能
  • 【面试题】作用域面试题
  • 08 定时器(下)
  • C++设计模式之适配器设计模式
  • Maven项目解决cannot resolve plugin maven-deploy-plugin:2.7
  • Postgresql源码(110)分析dsm动态共享内存分配与共享内存mq实例
  • 51单片机学习--蜂鸣器播放音乐
  • 【Vue组件eval方法的使用】
  • C++ 多文件结构和编译预处理命令
  • QT实现中英文键盘
  • java中并发编程CompletableFuture和supplyAsync的用法
  • chrony服务器
  • 春秋云镜 CVE-2021-24762
  • K8s中的Service
  • [软件工程] 全局分析规格说明书模板
  • 【JAVASE】封装
  • Java多线程(四)