Skip to content

Commit 55c5402

Browse files
committed
feat: improved caching by using two mutexes
1 parent e8e7665 commit 55c5402

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

pkg/cache/lru.go

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,39 +20,45 @@ type LRU struct {
2020
cache map[string]*node
2121
head *node
2222
tail *node
23-
mutex sync.Mutex
23+
cacheMutex sync.RWMutex
24+
listMutex sync.Mutex
2425
}
2526

2627
func (lru *LRU) Get(key string) string {
27-
lru.mutex.Lock()
28-
defer lru.mutex.Unlock()
28+
lru.cacheMutex.RLock()
2929
n := lru.cache[key]
3030
if n == nil {
3131
return ""
3232
}
33+
lru.cacheMutex.RUnlock()
3334

35+
lru.listMutex.Lock()
3436
lru.remove(n)
3537
lru.insertRight(n)
38+
lru.listMutex.Unlock()
3639

3740
return n.val
3841
}
3942

4043
func (lru *LRU) Set(key, value string) {
41-
lru.mutex.Lock()
42-
defer lru.mutex.Unlock()
44+
lru.cacheMutex.Lock()
4345
if n := lru.cache[key]; n != nil {
4446
lru.remove(n)
4547
}
46-
4748
n := &node{key: key, val: value}
4849
lru.cache[key] = n
50+
lru.cacheMutex.Unlock()
51+
lru.listMutex.Lock()
4952
lru.insertRight(n)
50-
53+
lru.listMutex.Unlock()
5154
// evict
55+
56+
lru.listMutex.Lock()
5257
if lru.capacity > lru.maxCapacity {
5358
delete(lru.cache, lru.tail.next.key)
5459
lru.remove(lru.tail.next)
5560
}
61+
lru.listMutex.Unlock()
5662

5763
}
5864

0 commit comments

Comments
 (0)