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 方法即可~
目录
相关文章
|
人工智能 算法 NoSQL
LRU算法的Java实现
LRU(Least Recently Used)算法用于淘汰最近最少使用的数据,常应用于内存管理策略中。在Redis中,通过`maxmemory-policy`配置实现不同淘汰策略,如`allkeys-lru`和`volatile-lru`等,采用采样方式近似LRU以优化性能。Java中可通过`LinkedHashMap`轻松实现LRUCache,利用其`accessOrder`特性和`removeEldestEntry`方法完成缓存淘汰逻辑,代码简洁高效。
692 0
|
设计模式 算法 搜索推荐
Java 设计模式之策略模式:灵活切换算法的艺术
策略模式通过封装不同算法并实现灵活切换,将算法与使用解耦。以支付为例,微信、支付宝等支付方式作为独立策略,购物车根据选择调用对应支付逻辑,提升代码可维护性与扩展性,避免冗长条件判断,符合开闭原则。
3169 35
|
存储 算法 搜索推荐
《数据之美》:Java数据结构与算法精要
本系列深入探讨数据结构与算法的核心原理及Java实现,涵盖线性与非线性结构、常用算法分类、复杂度分析及集合框架应用,助你提升程序效率,掌握编程底层逻辑。
|
存储 算法 安全
Java中的对称加密算法的原理与实现
本文详细解析了Java中三种常用对称加密算法(AES、DES、3DES)的实现原理及应用。对称加密使用相同密钥进行加解密,适合数据安全传输与存储。AES作为现代标准,支持128/192/256位密钥,安全性高;DES采用56位密钥,现已不够安全;3DES通过三重加密增强安全性,但性能较低。文章提供了各算法的具体Java代码示例,便于快速上手实现加密解密操作,帮助用户根据需求选择合适的加密方案保护数据安全。
1040 58
|
存储 人工智能 算法
从零掌握贪心算法Java版:LeetCode 10题实战解析(上)
在算法世界里,有一种思想如同生活中的"见好就收"——每次做出当前看来最优的选择,寄希望于通过局部最优达成全局最优。这种思想就是贪心算法,它以其简洁高效的特点,成为解决最优问题的利器。今天我们就来系统学习贪心算法的核心思想,并通过10道LeetCode经典题目实战演练,带你掌握这种"步步为营"的解题思维。
|
机器学习/深度学习 算法 Java
Java实现林火蔓延路径算法
记录正在进行的森林防火项目中林火蔓延功能,本篇文章可以较好的实现森林防火蔓延,但还存在很多不足,如:很多参数只能使用默认值,所以蔓延范围仅供参考。(如果底层设备获取的数据充足,那当我没说)。注:因林火蔓延涉及因素太多,如静可燃物载量、矿质阻尼系数等存在估值,所以得出的结果仅供参考。
752 5
|
存储 负载均衡 算法
我们来说一说 Java 的一致性 Hash 算法
我是小假 期待与你的下一次相遇 ~
861 1
|
运维 监控 算法
基于 Java 滑动窗口算法的局域网内部监控软件流量异常检测技术研究
本文探讨了滑动窗口算法在局域网流量监控中的应用,分析其在实时性、资源控制和多维分析等方面的优势,并提出优化策略,结合Java编程实现高效流量异常检测。
621 0
|
存储 监控 算法
企业上网监控场景下布隆过滤器的 Java 算法构建及其性能优化研究
布隆过滤器是一种高效的数据结构,广泛应用于企业上网监控系统中,用于快速判断员工访问的网址是否为违规站点。相比传统哈希表,它具有更低的内存占用和更快的查询速度,支持实时拦截、动态更新和资源压缩,有效提升系统性能并降低成本。
780 0
|
缓存 人工智能 算法
lru算法设计与实现
本文详细介绍了LRU(Least Recently Used,最近最少使用)缓存淘汰策略的原理与实现。LRU的核心思想是:越近被访问的数据,未来被再次访问的可能性越大。文章通过Java语言实现了一个支持O(1)时间复杂度操作的LRU缓存
594 0

热门文章

最新文章