实现一个LFU Cache

# 原理

LFU Cache 是Least Frequently Used Cache的缩写,记录缓存对象使用次数,当缓存满了之后,删除最少使用的缓存。

缓存容量为k,随着每次读取,使用次数都在变化,可以看成是从无尽序列中维护一个前K大的序列,当缓存满了之后,删除最小的元素。可以使用小顶堆来实现,Java中有对应的实现类PriorityQueue

首先实现一个缓存条目类,记录缓存的key,value,以及使用次数。

public class CacheEntry<K, V> implements Comparable<CacheEntry<K, V>> {
    private final K key;
    private V value;
    private int frequency;

    public CacheEntry(K key, V value) {
        this.key = key;
        this.value = value;
        this.frequency = 1;
    }

    @Override
    public int compareTo(CacheEntry<K, V> other) {
        int freqComparison = Integer.compare(frequency, other.frequency);
        return freqComparison != 0 ? freqComparison : key.hashCode() - other.key.hashCode();
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# ConcurrentHashMap + PriorityQueue + 读写锁 实现

import java.util.*;
import java.util.concurrent.locks.*;

class LFUCache<K, V> {
    private final int capacity;
    private final Map<K, CacheEntry<K, V>> cache;
    private final PriorityQueue<CacheEntry<K, V>> frequencyQueue;
    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private final Lock readLock = lock.readLock();
    private final Lock writeLock = lock.writeLock();

    public LFUCache(int capacity) {
        this.capacity = capacity;
        this.cache = new ConcurrentHashMap<>();
        this.frequencyQueue = new PriorityQueue<>();
    }

    public V get(K key) {
        readLock.lock();
        try {   
            CacheEntry<K, V> entry = cache.get(key);
            if (entry != null) {
                writeLock.lock();
                try {
                    updateFrequency(entry); // 更新使用频次
                } finally {
                    writeLock.unlock();
                }
                
                return entry.value;
            }
            return null;
        } finally {
            readLock.unlock();
        }
    }

    public void put(K key, V value) {
        writeLock.lock();
        try {
            CacheEntry<K, V> entry = cache.get(key);
            if (entry == null) {
                evictIfNeeded(); // 如果超过容量限制,则淘汰最低频次的条目
                entry = new CacheEntry<>(key, value);
                cache.put(key, entry);
                frequencyQueue.add(entry);
            } else {
                entry.value = value;
                updateFrequency(entry); // 更新使用频次
            }
        } finally {
            writeLock.unlock();
        }
    }

    private void updateFrequency(CacheEntry<K, V> entry) {
        frequencyQueue.remove(entry);
        entry.frequency++;
        frequencyQueue.add(entry);
    }

    private void evictIfNeeded() {
        if (cache.size() >= capacity) {
            CacheEntry<K, V> leastFrequentEntry = frequencyQueue.poll();
            if (leastFrequentEntry != null) {
                cache.remove(leastFrequentEntry.key);
            }
        }
    }

}
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
上次更新: 2023/11/14, 15:23:14
最近更新
01
go-admin-ui项目仿写练手1-登录页
06-29
02
maven依赖问题
06-17
03
JVM相关命令
02-21
更多文章>