Java - 快速手撕 LRU 算法

简介: Java - 快速手撕 LRU 算法
importjava.util.LinkedHashMap;
importjava.util.Map;
/*** @author Lux Sun* @date 2021/4/27*/publicclassLruCache<K, V>extendsLinkedHashMap<K, V> {
privateintcapacity;
/*** 构造函数* @param capacity: 初始容量* loadFactor: 加载因子, 一般是 0.75f* accessOrder: false 基于插入顺序; true 基于访问顺序(get一个元素后, 这个元素被加到最后, 使用了LRU最近最少被使用的调度算法)*/publicLruCache(intcapacity) {
super(16, 0.75f, true);
this.capacity=capacity;
    }
/*** LinkedHashMap 重写该函数, 详情见源码* @param eldest*/@OverrideprotectedbooleanremoveEldestEntry(Map.Entry<K, V>eldest) {
returnsize() >this.capacity;
    }
publicstaticvoidmain(String[] args) {
LruCache<String, Object>cache=newLruCache<>(2);
cache.put("1", 1);
cache.put("2", 2);
cache.put("3", 3);
cache.entrySet().forEach(System.out::println);
    }
}

结果输出

1. 2=2
2. 3=3

 

源码分析

/*** Returns <tt>true</tt> if this map should remove its eldest entry.* This method is invoked by <tt>put</tt> and <tt>putAll</tt> after* inserting a new entry into the map.  It provides the implementor* with the opportunity to remove the eldest entry each time a new one* is added.  This is useful if the map represents a cache: it allows* the map to reduce memory consumption by deleting stale entries.** <p>Sample use: this override will allow the map to grow up to 100* entries and then delete the eldest entry each time a new entry is* added, maintaining a steady state of 100 entries.* <pre>*     private static final int MAX_ENTRIES = 100;**     protected boolean removeEldestEntry(Map.Entry eldest) {*        return size() &gt; MAX_ENTRIES;*     }* </pre>** <p>This method typically does not modify the map in any way,* instead allowing the map to modify itself as directed by its* return value.  It <i>is</i> permitted for this method to modify* the map directly, but if it does so, it <i>must</i> return* <tt>false</tt> (indicating that the map should not attempt any* further modification).  The effects of returning <tt>true</tt>* after modifying the map from within this method are unspecified.** <p>This implementation merely returns <tt>false</tt> (so that this* map acts like a normal map - the eldest element is never removed).** @param    eldest The least recently inserted entry in the map, or if*           this is an access-ordered map, the least recently accessed*           entry.  This is the entry that will be removed it this*           method returns <tt>true</tt>.  If the map was empty prior*           to the <tt>put</tt> or <tt>putAll</tt> invocation resulting*           in this invocation, this will be the entry that was just*           inserted; in other words, if the map contains a single*           entry, the eldest entry is also the newest.* @return   <tt>true</tt> if the eldest entry should be removed*           from the map; <tt>false</tt> if it should be retained.*/protectedbooleanremoveEldestEntry(Map.Entry<K,V>eldest) {
returnfalse;
}
voidafterNodeInsertion(booleanevict) { // possibly remove eldestLinkedHashMap.Entry<K,V>first;
if (evict&& (first=head) !=null&&removeEldestEntry(first)) {
Kkey=first.key;
removeNode(hash(key), key, null, false, true);
    }
}
  • 在 if 语句里,默认 removeEldestEntry 函数返回都是 false,而里面其实就是 LRU 算法的关键代码,我们只需要激活这个条件即可,所以在我们的代码里重写 removeEldestEntry 方法即可~
目录
相关文章
|
3天前
|
算法 安全 Java
性能工具之 JMeter 自定义 Java Sampler 支持国密 SM2 算法
【4月更文挑战第28天】性能工具之 JMeter 自定义 Java Sampler 支持国密 SM2 算法
14 1
性能工具之 JMeter 自定义 Java Sampler 支持国密 SM2 算法
|
3天前
|
存储 缓存 算法
面试遇到算法题:实现LRU缓存
V哥的这个实现的关键在于维护一个双向链表,它可以帮助我们快速地访问、更新和删除最近最少使用的节点,同时使用哈希表来提供快速的查找能力。这样,我们就可以在 O(1) 的时间复杂度内完成所有的缓存操作。哈哈干净利索,回答完毕。
|
8天前
|
设计模式 算法 Java
[设计模式Java实现附plantuml源码~行为型]定义算法的框架——模板方法模式
[设计模式Java实现附plantuml源码~行为型]定义算法的框架——模板方法模式
|
9天前
|
搜索推荐 算法 Java
Java实现的常用八种排序算法
提到数据结构与算法,无法避免的一点就包含排序,熟练的掌握各种排序算法则是一个程序员必备的素质之一,除此之外,排序算法也是当下各大技术公司比较喜欢问的技术点,所以,就这一点JavaBuild整理了常见的8种排序算法
6 0
|
14天前
|
机器学习/深度学习 数据采集 算法
使用 Java 实现机器学习算法
【4月更文挑战第19天】Java在数据驱动时代为机器学习提供支持,具备丰富的数学和数据结构库,适用于实现线性回归、决策树、SVM和随机森林等算法。实现时注意数据预处理、模型选择、评估指标和可视化。利用Java的库和编程能力可构建高效模型,但需按问题需求选择合适技术和优化方法。
|
24天前
|
缓存 算法 Java
如何实现缓存与LRU算法以及惰性过期
如何实现缓存与LRU算法以及惰性过期
31 1
|
24天前
|
算法 安全 Java
java代码 实现AES_CMAC 算法测试
该代码实现了一个AES-CMAC算法的简单测试,使用Bouncy Castle作为安全提供者。静态变量K定义了固定密钥。`Aes_Cmac`函数接受密钥和消息,返回AES-CMAC生成的MAC值。在`main`方法中,程序对给定的消息进行AES-CMAC加密,然后模拟接收ECU的加密结果并进行比较。如果两者匹配,输出&quot;验证成功&quot;,否则输出&quot;验证失败&quot;。辅助方法包括将字节转为16进制字符串和将16进制字符串转为字节。
|
1月前
|
搜索推荐 Java
Java排序算法
Java排序算法
18 0
|
1月前
|
搜索推荐 Java
Java基础(快速排序算法)
Java基础(快速排序算法)
24 4
|
12天前
|
机器学习/深度学习 人工智能 算法
基于DCT和扩频的音频水印嵌入提取算法matlab仿真
本文介绍了结合DCT和扩频技术的音频水印算法,用于在不降低音质的情况下嵌入版权信息。在matlab2022a中实现,算法利用DCT进行频域处理,通过扩频增强水印的隐蔽性和抗攻击性。核心程序展示了水印的嵌入与提取过程,包括DCT变换、水印扩频及反变换步骤。该方法有效且专业,未来研究将侧重于提高实用性和安全性。