LRU原理
LRU(Least recently used,最近最少使用)算法根据数据的历史访问记录来进行淘汰数据,其核心思想是“如果数据最近被访问过,那么将来被访问的几率也更高”。
实现方式
要实现LRU算法,有 2 种实现方式。
第一种,是使用Java中现成的API —— LinkedHashMap。它在HashMap的基础增加了按照访问顺序排序的功能,非常适合LRU的实现。
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
public class LRUCacheByAPI extends LinkedHashMap {
private static final float DEFAULE_LOAD_FACTOR = 0.75f;
private int capaciticy;
public LRUCacheByAPI(int capaciticy) { super((int) Math.ceil(capaciticy / DEFAULE_LOAD_FACTOR), DEFAULE_LOAD_FACTOR, true); this.capaciticy = capaciticy; }
@Override protected boolean removeEldestEntry(Map.Entry eldest) { return size() > capaciticy; } }
|
第二种,是使用哈希 + 双向链表的方式,自己造轮子实现。用双向链表的原因是删除节点快,用哈希原因是查找快,使得put,get较快。
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
|
public class LRUCache<K, V> {
class Node { private K k; private V v; private Node pre, next;
public Node() { }
public Node(K k, V v) { this.k = k; this.v = v; } }
class DoubleLinkedList {
Node head, tail;
private int size;
public DoubleLinkedList() { head = new Node(); tail = new Node(); head.next = tail; tail.pre = head; size = 0; }
public void addFirst(Node node) { node.next = head.next; node.pre = head; head.next.pre = node; head.next = node; size++; }
public void remove(Node node) { node.pre.next = node.next; node.next.pre = node.pre; size--; }
public Node removeLast() { if (size > 0) { Node last = tail.pre; remove(last); return last; } else { return null; } }
public int size() { return size; } }
private HashMap<K, Node> map; private DoubleLinkedList cache;
private int capaciticy;
public LRUCache(int capaciticy) { this.capaciticy = capaciticy; map = new HashMap<>(); cache = new DoubleLinkedList(); }
public V get(K key) { if (!map.containsKey(key)) { return null; } V value = map.get(key).v; put(key, value); return value; }
public void put(K key, V value) { Node node = new Node(key, value); if (map.containsKey(key)) { cache.remove(map.get(key)); cache.addFirst(node); map.put(key, node); } else { if (capaciticy == cache.size()) { Node last = cache.removeLast(); map.remove(last.k); } map.put(key, node); cache.addFirst(node); } } }
|