Skip to content

Commit 72cfa42

Browse files
committed
fixed critical sections in DeleteExpired
1 parent da44c9e commit 72cfa42

File tree

2 files changed

+7
-4
lines changed

2 files changed

+7
-4
lines changed

cache.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,12 +201,18 @@ func (c *Cache[K, V]) Get(key K) (value V, ok bool) {
201201

202202
// DeleteExpired all expired items from the cache.
203203
func (c *Cache[K, V]) DeleteExpired() {
204-
for _, key := range c.cache.Keys() {
204+
c.mu.Lock()
205+
keys := c.cache.Keys()
206+
c.mu.Unlock()
207+
208+
for _, key := range keys {
209+
c.mu.Lock()
205210
// if is expired, delete it and return nil instead
206211
item, ok := c.cache.Get(key)
207212
if ok && item.Expired() {
208213
c.cache.Delete(key)
209214
}
215+
c.mu.Unlock()
210216
}
211217
}
212218

cache_test.go

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package cache_test
22

33
import (
44
"math/rand"
5-
"runtime"
65
"sync"
76
"testing"
87
"time"
@@ -121,6 +120,4 @@ func TestCallJanitor(t *testing.T) {
121120
if len(keys) != 0 {
122121
t.Errorf("want items is empty but got %d", len(keys))
123122
}
124-
125-
runtime.GC()
126123
}

0 commit comments

Comments
 (0)