如何在Java中实现LRU缓存? [英] How would you implement an LRU cache in Java?

查看:158
本文介绍了如何在Java中实现LRU缓存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请不要说EHCache或OSCache等。假设为了这个问题的目的,我想使用SDK实现自己的(通过做)。鉴于缓存将在多线程环境中使用,您将使用哪些数据结构?我已经使用 LinkedHashMap 实现了一个 Collections#synchronizeMap ,但是如果任何新的并发集合将是更好的候选人,我很好奇。

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#synchronizeMap 我上面提到的实现。很高兴知道我不只是忽略了一些东西。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆