代码之家  ›  专栏  ›  技术社区  ›  Elimination

使用内置数据结构实现LRU缓存[重复]

  •  0
  • Elimination  · 技术社区  · 7 年前

    这个问题已经有了答案:

    我想用Java的内置数据结构在Java中实现一个简单的LRU缓存。

    其思想是使用一个映射和一个双重链接列表(DLL)。

    所以我用的地图 HashMap . 我现在面临的问题是,我想要一个哈希图中的项目 将指向 到dll中的相应项,但我无权访问 LinkedList .

    在不创建自己的新数据结构的情况下,什么是合理的解决方案?

    2 回复  |  直到 7 年前
        1
  •  2
  •   Mark Rotteveel    7 年前

    可以使用java LinkedHashMap 和覆盖 removeEldestEntry 实现LRU缓存

    public class SimpleLru<K, V> extends LinkedHashMap<K, V>{
    
        final int cacheSize;
    
        public SimpleLru(int cacheSize) {
            this.cacheSize = cacheSize;
        }
    
        @Override
        protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
            return this.size() > this.cacheSize;
        }
    
        public static void main(String[] args) {
            SimpleLru<String, Integer> m = new SimpleLru<>(2); // Max 2
            m.put("k1", 1); // k1:1
            m.put("k2", 2); // k1:1, k2:2
            m.put("k3", 3); // k2:2, k3:3
        }
    }
    

    如果要有线程安全版本,可以使用:

    public class ConcurrentLru<K, V> {
    
        final Object mutex = new Object();
        final Map<K, V> cache;
    
        public ConcurrentLru(final int cacheSize) {
            this.cache = new LinkedHashMap<K, V>() {
    
                @Override
                protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
                    return this.size() > cacheSize;
                }
            };
        }
    
        public void put(K k, V v) {
            synchronized (this.mutex) { this.cache.put(k, v); }
        }
    
        public boolean contains(K k) {
            synchronized (this.mutex) { return this.cache.containsKey(k); }
        }
    
        public V remove(K k) {
            synchronized (this.mutex) { return this.cache.remove(k); }
        }
    
        public V get(K k) {
            synchronized (this.mutex) { return this.cache.get(k); }
        }
    }
    
        2
  •  1
  •   ᴇʟᴇvᴀтᴇ    7 年前

    我会试图劝阻您不要重新设计一个拥有大量优秀现有实现的轮子。例如,Google Guava's caches 太棒了。它们提供了几种方法来逐出缓存的元素。也, Caffeine (由在瓜娃缓存工作的开发人员编写),以及 EhCache 历史悠久。

    如果你有什么理由要自己做,看看这个 question and the answers .