您将如何在 Java 中实现 LRU 缓存? [英] How would you implement an LRU cache in Java?
问题描述
请不要说 EHCache 或 OSCache 等.为了这个问题的目的,假设我想仅使用 SDK 来实现我自己的(边做边学).鉴于缓存将用于多线程环境,您会使用哪种数据结构?我已经使用 LinkedHashMap 和Collections#synchronizedMap,但我很好奇是否有任何新的并发集合是更好的候选者.
Please don't say EHCache or OSCache, etc. Assume for purposes of this question that I want to implement my own using just the SDK (learning by doing). Given that the cache will be used in a multithreaded environment, which datastructures would you use? I've already implemented one using LinkedHashMap and Collections#synchronizedMap, but I'm curious if any of the new concurrent collections would be better candidates.
更新:我刚刚阅读了Yegge 的最新消息 当我发现这个金块时:
UPDATE: I was just reading through Yegge's latest when I found this nugget:
如果您需要恒定时间访问并想要维护插入顺序,那么您不能比 LinkedHashMap 做得更好,这是一个真正美妙的数据结构.它可能更精彩的唯一方法是如果有一个并发版本.但是唉.
If you need constant-time access and want to maintain the insertion order, you can't do better than a LinkedHashMap, a truly wonderful data structure. The only way it could possibly be more wonderful is if there were a concurrent version. But alas.
在使用我上面提到的 LinkedHashMap
+ Collections#synchronizedMap
实现之前,我的想法几乎完全相同.很高兴知道我没有忽略一些东西.
I was thinking almost exactly the same thing before I went with the LinkedHashMap
+ Collections#synchronizedMap
implementation I mentioned above. Nice to know I hadn't just overlooked something.
根据目前的答案,对于高并发 LRU 来说,我最好的选择是扩展 ConcurrentHashMap 使用一些与 LinkedHashMap
使用的相同的逻辑.
Based on the answers so far, it sounds like my best bet for a highly concurrent LRU would be to extend ConcurrentHashMap using some of the same logic that LinkedHashMap
uses.
推荐答案
如果我今天从头再来一次,我会使用 Guava 的 CacheBuilder
.
If I were doing this again from scratch today, I'd use Guava's CacheBuilder
.
这篇关于您将如何在 Java 中实现 LRU 缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!