利用LinkHashMap实现LRU CACHE

LRU (Least Recently Used) 是一种缓存失效策略,即指定最大缓存 item 的数量,在缓存数量不足时将最近最少使用的缓存淘汰掉。

不失一般的,我们假定对缓存主要有两种操作:

  1. PUT,即将数据放入缓存中;
  2. GET,即尝试从缓存中获取数据。

以上两种操作都会被视为使用了缓存,当缓存空间不足时,将最近最少使用的数据从缓存中移除。使用 JAVA,我们应当如何实现以上的需求呢?

利用 HashMap 和 双向链表实现

思考上述需求后,可以有一个简单的解决思路:利用 HashMap 存储缓存数据,而后将数据节点组成一个双向链表,每次 PUT 或 GET 操作后都将操作涉及到的缓存数据节点插入链表的尾部,那么在缓存已满需要淘汰数据时就可以将链表头部指向的数据节点删除了。代码如下:

public class LRUCache<K, V> {
    private int capacity;

    private Map<K, Node<K, V>> cacheData;

    private Node<K, V> head;

    private Node<K, V> tail;

    private static class Node<K, V> {
        private K key;

        private V value;

        private Node<K, V> pre;

        private Node<K, V> next;

        private Node(K key, V value) {
            this.key = key;
            this.value = value;
        }


    }

    public LRUCache(int capacity) {

        if (capacity <= 0) {
            throw new InvalidParameterException("capacity 必须大于0");
        }

        this.capacity = capacity;

        //初始化 HashMap 大小为 capacity, 负载因子为 0.75
        this.cacheData = new HashMap<>(this.capacity, 0.75f);

        // sentinel 方便处理
        this.head = new Node<>(null, null);
        this.tail = new Node<>(null, null);

        this.head.next = this.tail;

        this.tail.pre = this.head;
    }

    public void put(K key, V value) {

        if (null == key) {
            throw new NullPointerException("key 不能为 null");
        }

        Node<K, V> node = cacheData.get(key);
        //第一次 PUT 生成node
        if (null == node) {
            node = new Node<>(key, value);
        } else {
            deQueue(node);
        }

        //放入尾部
        putToTail(node);

        //是否需要淘汰数据
        removeLruIfNecessary();

        //放入缓存中
        cacheData.put(key, node);
    }

    /**
     * 删除最近最少使用的数据
     */
    private void removeLruIfNecessary() {
        if (cacheData.size() >= capacity) {
            Node<K, V> remove = head.next;
            //从链表中移除
            deQueue(remove);
            cacheData.remove(remove.key);
        }
    }

    public V get(K key) {
        if (null == key) {
            throw new NullPointerException("key 不能为 null");
        }
        Node<K, V> node = cacheData.get(key);
        if (null == node) {
            return null;
        }

        //从链表中移除
        deQueue(node);

        //加入链表尾部
        putToTail(node);

        return node.value;
    }


    private void deQueue(Node<K, V> node) {
        node.pre.next = node.next;
        node.next.pre = node.pre;
        node.next = node.pre = null;
    }

    private void putToTail(Node<K, V> node) {
        node.pre = tail.pre;
        node.next = tail;
        node.pre.next = node;
        tail.pre = node;
    }
}

进行简单的测试:

    public static void main(String[] args) {
        LRUCache<Integer, Integer> lruCache = new LRUCache<>(10);

        for (int i = 0; i < 20; i++) {
            lruCache.put(i, i);
        }

        for (int j = 19; j >= 10; j--) {
            lruCache.get(j);
        }
    }
put(14,14)时
get(16)时

利用LinkedHashMap 实现

上面的实现其实还是有些复杂,其实 JDK 中的 LinkedHashMap 早就帮我们实现好了需要的功能。LinkedHashMap 是HashMap 的一个子类,保存了记录的插入顺序,在用 Iterator 遍历 LinkedHashMap 时,先得到的记录肯定是先插入的.也可以在构造时用带参数,按照应用次数排序。

使用 LinkedHashMap 构造 LRU cache的代码如下:

public class LRUCache<K, V> {

    private LinkedHashMap<K, V> linkedHashMap;

    public LRUCache(int capacity) {
        linkedHashMap = new LinkedHashMap<K, V>(capacity, 0.75f, true) {
            @Override
            protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
                return size() > capacity;
            }
        };
    }

    public void put(K key, V value) {
        linkedHashMap.put(key, value);
    }

    public V get(K key) {
        return linkedHashMap.get(key);
    }
}

可以看到,只需要指定构造函数的 accessOrder 为true,再重写 LinkedHashMapremoveEldestEntry 方法,使其在容量超过预设大小时删除最老元素即可。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Collection & Map Collection 子类有 List 和 Set List --> Array...
    任教主来也阅读 3,313评论 1 9
  • 欢迎访问我的博客:http://wangnan.tech 概述 HashMap 是无序的,HashMap 在 pu...
    GhostStories阅读 1,723评论 0 7
  • 理论总结 它要解决什么样的问题? 数据的访问、存取、计算太慢、太不稳定、太消耗资源,同时,这样的操作存在重复性。因...
    jiangmo阅读 3,147评论 0 11
  • 本文根据jdk1.7 HashMap 结构特点 1、table是一个Entry[]数组类型,而Entry实际上就是...
    eqgao阅读 364评论 0 2
  • 亲爱的老爸老妈们,一路走来,我们已经学习了11周了,大家有什么特别感兴趣的话题,请在群里告诉我们志愿者们,祝大家身...
    一三心理阅读 421评论 0 0

友情链接更多精彩内容