10000 docs: update lru cache implement · lhzctf/advanced-java@9b7a06b · GitHub
[go: up one dir, main page]

Skip to content

Commit 9b7a06b

Browse files
committed
docs: update lru cache implement
1 parent 6ece259 commit 9b7a06b

File tree

3 files changed

+22
-11
lines changed

3 files changed

+22
-11
lines changed
35.7 KB
Loading

docs/high-concurrency/images/lru.png

25.6 KB
Loading

docs/high-concurrency/redis-expiration-policies-and-lru.md

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -51,33 +51,44 @@ Redis 内存淘汰机制有以下几个:
5151

5252
### 手写一个 LRU 算法
5353

54+
LRU 就是 Least Recently Used 的缩写,翻译过来就是“最近最少使用”。也就是说 LRU 算法会将最近最少用的缓存移除,让给最新使用的缓存。而往往最常读取的,也就是读取次数最多的,所以利用好 LRU 算法,我们能够提供对热点数据的缓存效率,能够提高缓存服务的内存使用率。
55+
56+
那么如何实现呢?
57+
58+
其实,实现的思路非常简单,就像下面这张图种描述的一样。
59+
60+
![](./images/lru.png)
61+
5462
你可以现场手写最原始的 LRU 算法,那个代码量太大了,似乎不太现实。
5563

5664
不求自己纯手工从底层开始打造出自己的 LRU,但是起码要知道如何利用已有的 JDK 数据结构实现一个 Java 版的 LRU。
5765

66+
![](./images/lru-cache.png)
67+
5868
```java
59-
class LRUCache<K, V> extends LinkedHashMap<K, V> {
60-
private final int CACHE_SIZE;
69+
public class LRUCache<K, V> extends LinkedHashMap<K, V> {
70+
private int capacity;
6171

6272
/**
6373
* 传递进来最多能缓存多少数据
6474
*
65-
* 8000 @param cacheSize 缓存大小
75+
* @param capacity 缓存大小
6676
*/
67-
public LRUCache(int cacheSize) {
68-
// true 表示让 linkedHashMap 按照访问顺序来进行排序,最近访问的放在头部,最老访问的放在尾部。
69-
super((int) Math.ceil(cacheSize / 0.75) + 1, 0.75f, true);
70-
CACHE_SIZE = cacheSize;
77+
public LRUCache(int capacity) {
78+
super(capacity, 0.75f, true);
79+
this.capacity = capacity;
7180
}
7281

7382
/**
74-
* 钩子方法,通过put新增键值对的时候,若该方法返回true
75-
* 便移除该map中最老的键和值
83+
* 如果map中的数据量大于设定的最大容量,返回true,再新加入对象时删除最老的数据
84+
*
85+
* @param eldest 最老的数据项
86+
* @return true则移除最老的数据
7687
*/
7788
@Override
7889
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
79-
// 当 map中的数据量大于指定的缓存个数的时候,就自动删除最老的数据。
80-
return size() > CACHE_SIZE;
90+
// 当 map中的数据量大于指定的缓存个数的时候,自动移除最老的数据
91+
return size() > capacity;
8192
}
8293
}
8394
```

0 commit comments

Comments
 (0)
0