LRU 算法的两种实现方式

张天宇 on 2020-08-17

LRUCache 的两种实现方式,借助和不借助 LinkedHashMap。

HashMap + LinkedList

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
import java.util.HashMap;
import java.util.LinkedList;

public class Main {

static class LRUCache<K, V> {
// 缓冲容量
private final int cacheSize;
// 双向链表,存储缓存
private LinkedList<K> cacheList = new LinkedList<>();
// 储存缓存的key,用来计算是否命中,命中率则遍历链表
private HashMap<K, V> map = new HashMap<>();

public LRUCache(int cacheSize) {
this.cacheSize = cacheSize;
}

public synchronized void put(K key, V val) {
// 未命中
if (!map.containsKey(key)) {
// 如果超过了缓存,将最少访问的移除
if (map.size() >= cacheSize) {
map.remove(cacheList.removeLast());
}
cacheList.addFirst(key);
map.put(key, val);
} else {
// 命中,将链表元素往前移动,更新map
moveToFirst(key);
map.put(key, val);
}
}

public V get(K key) {
// 是否命中
if (!map.containsKey(key)) {
return null;
}
// 移动到前面来
moveToFirst(key);
return map.get(key);
}

// 移动到双链表前面
private synchronized void moveToFirst(K key) {
cacheList.remove(key);
cacheList.addFirst(key);
}

@Override
public String toString() {
return cacheList.toString();
}
}

public static void main(String[] args) {
LRUCache<String, String> lruCache = new LRUCache<String, String>(4);
lruCache.put("C", null);
lruCache.put("A", null);
lruCache.put("D", null);
lruCache.put("B", null);
lruCache.put("E", null);
lruCache.put("B", null);
lruCache.put("A", null);
lruCache.put("B", null);
lruCache.put("C", null);
lruCache.put("D", null);
System.out.println(lruCache);
}
}
/**
[D, C, B, A]
**/

LinkedHashMap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class LRUCache extends LinkedHashMap<Integer, Integer> {
private int capacity;

public LRUCache(int capacity) {
super(capacity, 0.75f, true);
this.capacity = capacity;
}

public int get(int key) {
return super.getOrDefault(key, -1);
}

public void put(int key, int val) {
super.put(key, val);
}

@Override
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
return size() > capacity;
}
}