Skip to content

Commit 03a1b4b

Browse files
ahmedtdk8s-publishing-bot
authored andcommitted
LRUExpireCache: Allow removing multiple keys under lock
Kubernetes-commit: e83baddbb1a7b8f88db357fcefc8c7f3dde4856c
1 parent bc0a03b commit 03a1b4b

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

pkg/util/cache/lruexpirecache.go

+13
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,19 @@ func (c *LRUExpireCache) Remove(key interface{}) {
136136
delete(c.entries, key)
137137
}
138138

139+
// RemoveAll removes all keys that match predicate.
140+
func (c *LRUExpireCache) RemoveAll(predicate func(key any) bool) {
141+
c.lock.Lock()
142+
defer c.lock.Unlock()
143+
144+
for key, element := range c.entries {
145+
if predicate(key) {
146+
c.evictionList.Remove(element)
147+
delete(c.entries, key)
148+
}
149+
}
150+
}
151+
139152
// Keys returns all unexpired keys in the cache.
140153
//
141154
// Keep in mind that subsequent calls to Get() for any of the returned keys

pkg/util/cache/lruexpirecache_test.go

+14
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,20 @@ func TestSimpleRemove(t *testing.T) {
6767
expectNotEntry(t, c, "long-lived")
6868
}
6969

70+
func TestSimpleRemoveAll(t *testing.T) {
71+
c := NewLRUExpireCache(10)
72+
c.Add("long-lived", "12345", 10*time.Hour)
73+
c.Add("other-long-lived", "12345", 10*time.Hour)
74+
c.RemoveAll(func(k any) bool {
75+
return k.(string) == "long-lived"
76+
})
77+
78+
assertKeys(t, c.Keys(), []any{"other-long-lived"})
79+
80+
expectNotEntry(t, c, "long-lived")
81+
expectEntry(t, c, "other-long-lived", "12345")
82+
}
83+
7084
func TestExpiredGet(t *testing.T) {
7185
fakeClock := testingclock.NewFakeClock(time.Now())
7286
c := NewLRUExpireCacheWithClock(10, fakeClock)

0 commit comments

Comments
 (0)