最直观的LRU缓存淘汰算法解析(附Java代码)

简介

LRU(Least Recently Used)即最近最久未使用,是一种常用的缓存淘汰算法。LRU的主要目的是在有限的缓存空间里进行缓存的更新和维护,将最近最久未使用的缓存数据淘汰,替换为新的缓存数据。

原理

LRU维护一个双向链表,越靠近表头的位置表明缓存数据离现在越近的时间使用过,越靠近表尾的位置表明缓存数据越久未使用过,表尾的数据则是所有缓存数据中最久未使用过的。

通过维护这个链表,确保始终能够找出最近最久未使用的缓存数据。当新的缓存数据插入时,如果缓存空间不足,则将位于表尾的缓存数据删除,腾出一个空间供新的缓存数据存储,并将新数据插入至表头。

图解

0.LRU的数据结构如下

由一个双向链表和一个hash表组成,hash表通过key能够获取到双向链表中的每个节点的引用。这一设计主要是为了在O(1)的时间复杂度下可以直接定位目标节点。

1.查找缓存数据

如果缓存数据存在,所命中的缓存则是最新使用的,需要从双向链表中移出,并移动到表头。

首先通过hash表直接获取到目标节点

然后将目标节点从双向链表中移出,维护相邻节点的指针,并将目标节点添加至表头。保证整个链表的语义正确性。

返回该节点存储的value即可。

2.新插入缓存数据

这里我们假设当前LRU的最大容量为5,当链表长度未达到最大容量时,直接将新的缓存数据添加到双向链表的表头。并记录在hash表中即可,不再赘述。

当链表长度已经达到最大容量,此时添加新的数据就会超出容量,因此必须把位于表尾的最近最久未使用的缓存数据删除掉。

3.删除和修改

删除和修改节点不涉及到节点移动,都是通过hash表直接定位到目标节点,如果是删除则解相邻节点引用。如果是修改则直接修改节点的value值。

代码

public class LRUCache<K, V> {
    @AllArgsConstructor
    class Node {
        Node prev;
        Node next;
        K key;
        V value;
    }
    private Node head;
    private Node tail;
    private final Map<K, Node> map;
    private final int capacity;

    public LRUCache(int capacity) {
        map = new HashMap<>();
        this.capacity = capacity;
    }

    public V get(K key) {
        if (map.containsKey(key)) {
            Node node = map.get(key);
            this.move2Head(node);
            return node.value;
        }
        return null;
    }

    public void push(K key, V value) {
        Node node = new Node(null, this.head, key, value);
        if (this.head != null) {
            this.head.prev = node;
        }
        this.head = node;
        map.put(key, node);

        // 如果list为空 尾节点也和头节点一样指向node
        if (this.tail == null) {
            this.tail = node;
        }

        // 溢出,删除尾节点(最久未使用的节点)
        if (map.size() > this.capacity) {
            map.remove(this.tail.key);
            this.tail.prev.next = null;
            this.tail = this.tail.prev;
        }
    }

    public void move2Head(Node node) {
        if (node.prev == null) { // 头节点不必动
            return;
        }
        this.remove(node);
        node.prev = null;
        node.next = this.head;
        if (this.head != null) {
            this.head.prev = node;
        }
        this.head = node;
    }

    public void remove(Node node) {
        if (node.prev != null) {
            node.prev.next = node.next;
        } else { // 如果是头节点要更新头节点标记
            this.head = node.next;
        }
        if (node.next != null) {
            node.next.prev = node.prev;
        } else { // 如果是尾节点要更新尾节点标记
            this.tail = node.prev;
        }
    }

    public void remove(K key) {
        if (map.containsKey(key)) {
            Node node = map.get(key);
            this.remove(node);
            this.map.remove(key);
        }
    }

    public void showList() {
        Node t = this.head;
        while (t != null) {
            System.out.println("key: " + t.key + "    value: " + t.value);
            t = t.next;
        }
        if (this.head != null) {
            System.out.println("this.head:" + this.head.key + "    this.tail:" + this.tail.key);
        }
        System.out.println("===========");
    }

    public static void main(String[] args) {
        LRUCache<String, String> cache = new LRUCache<>(3);
        // 初始化添加
        cache.push("a", "hello");
        cache.push("b", "world");
        cache.push("c", "apple");
        cache.showList();
        // 最大容量添加测试
        cache.push("d", "code");
        cache.showList();
        // 查找测试
        String c = cache.get("c");
        System.out.println("get c: " + c);
        cache.showList();
        //修改测试
        cache.push("a","aloha");
        cache.showList();
        //删除测试
        cache.remove("d");
        cache.showList();
    }
}

运行结果如下:

key: c    value: apple
key: b    value: world
key: a    value: hello
this.head:c    this.tail:a
===========
key: d    value: code
key: c    value: apple
key: b    value: world
this.head:d    this.tail:b
===========
get c: apple
key: c    value: apple
key: d    value: code
key: b    value: world
this.head:c    this.tail:b
===========
key: a    value: aloha
key: c    value: apple
key: d    value: code
this.head:a    this.tail:d
===========
key: a    value: aloha
key: c    value: apple
this.head:a    this.tail:c
===========

这段LRU算法的简易实现代码,定义了一个 LRUCache<K, V> 结构,可以通过泛型选择缓存的key和value的类型。在测试中,选择了String作为缓存的key和value。

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java实现LRU缓存淘汰算法的方法与Python类似,也可以使用哈希表和双向链表来实现。下面是一个Java实现的LRU缓存淘汰算法代码示例: ```java class LRUCache { private Map<Integer, Node> map; private int capacity; private Node head; private Node tail; public LRUCache(int capacity) { this.capacity = capacity; map = new HashMap<>(); head = new Node(0, 0); tail = new Node(0, 0); head.next = tail; tail.prev = head; } public int get(int key) { if (map.containsKey(key)) { Node node = map.get(key); remove(node); add(node); return node.value; } else { return -1; } } public void put(int key, int value) { if (map.containsKey(key)) { Node node = map.get(key); node.value = value; remove(node); add(node); } else { if (map.size() == capacity) { Node node = tail.prev; remove(node); map.remove(node.key); } Node node = new Node(key, value); map.put(key, node); add(node); } } private void add(Node node) { Node next = head.next; head.next = node; node.prev = head; node.next = next; next.prev = node; } private void remove(Node node) { Node prev = node.prev; Node next = node.next; prev.next = next; next.prev = prev; } private class Node { int key; int value; Node prev; Node next; public Node(int key, int value) { this.key = key; this.value = value; } } } ``` 在这个实现中,我们同样使用了一个哈希表来查询节点是否存在以及快速删除节点,使用一个双向链表来维护缓存中节点的顺序。当有新的节点被访问时,我们将其移到链表头部,并且当缓存空间不足时,我们淘汰链表尾部的节点。同时,我们使用了一个Node内部类来封装节点的key和value,以及前驱和后继节点的指针。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值