Skip to content

Commit 5ada1c0

Browse files
committed
common/lru: synchronization
1 parent ccf78d2 commit 5ada1c0

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

Diff for: common/lru/blob_lru.go

+9-2
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,19 @@ package lru
1818

1919
import (
2020
"math"
21+
"sync"
2122

2223
"github.com/hashicorp/golang-lru/simplelru"
2324
)
2425

25-
// SizeConstrainedLRU is a wrapper around simplelru.LRU, which
26-
// adds a byte-size constraint.
26+
// SizeConstrainedLRU is a wrapper around simplelru.LRU. The simplelru.LRU is capable
27+
// of item-count constraints, but is not capable of enforcing a byte-size constraint,
28+
// hence this wrapper.
2729
type SizeConstrainedLRU struct {
2830
size uint64
2931
maxSize uint64
3032
lru *simplelru.LRU
33+
lock sync.RWMutex
3134
}
3235

3336
// NewSizeConstraiedLRU creates a new SizeConstrainedLRU.
@@ -50,6 +53,8 @@ func (c *SizeConstrainedLRU) Set(key []byte, value []byte) (evicted bool) {
5053

5154
// Add adds a value to the cache. Returns true if an eviction occurred.
5255
func (c *SizeConstrainedLRU) Add(key string, value string) (evicted bool) {
56+
c.lock.Lock()
57+
defer c.lock.Unlock()
5358
targetSize := c.size + uint64(len(value))
5459
for targetSize > c.maxSize {
5560
evicted = true
@@ -67,6 +72,8 @@ func (c *SizeConstrainedLRU) Add(key string, value string) (evicted bool) {
6772

6873
// Get looks up a key's value from the cache.
6974
func (c *SizeConstrainedLRU) Get(key []byte) []byte {
75+
c.lock.RLock()
76+
defer c.lock.RUnlock()
7077
if v, ok := c.lru.Get(string(key)); ok {
7178
return []byte(v.(string))
7279
}

0 commit comments

Comments
 (0)