-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleast_recently_used.go
48 lines (40 loc) · 1.11 KB
/
least_recently_used.go
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
package cache_replacement_policies
import "time"
// The least recently used item will be evicted
type lruCachePolicy struct {
lastUsedAt map[string]int64
leastRecentlyUsedKey string
}
func NewLRUCachePolicy() CachePolicy {
return &lruCachePolicy{lastUsedAt: map[string]int64{}}
}
func (cp lruCachePolicy) PickKeyToEvict() string {
return cp.leastRecentlyUsedKey
}
func (cp *lruCachePolicy) OnKeySet(key string) {
if cp.leastRecentlyUsedKey == "" {
cp.leastRecentlyUsedKey = key
}
cp.lastUsedAt[key] = time.Now().Unix()
}
func (cp *lruCachePolicy) OnKeyGet(key string) {
if cp.leastRecentlyUsedKey == "" {
cp.leastRecentlyUsedKey = key
}
cp.lastUsedAt[key] = time.Now().Unix()
}
func (cp *lruCachePolicy) OnKeyEviction(key string) error {
delete(cp.lastUsedAt, key)
leastRecentlyUsed := struct {
key string
timestamp int64
}{timestamp: time.Now().Unix()}
for key, timestamp := range cp.lastUsedAt {
if timestamp < leastRecentlyUsed.timestamp {
leastRecentlyUsed.timestamp = timestamp
leastRecentlyUsed.key = key
}
}
cp.leastRecentlyUsedKey = leastRecentlyUsed.key
return nil
}