Skip to content

Commit

Permalink
LRUExpireCache: Allow removing multiple keys under lock
Browse files Browse the repository at this point in the history
Kubernetes-commit: e83baddbb1a7b8f88db357fcefc8c7f3dde4856c
  • Loading branch information
ahmedtd authored and k8s-publishing-bot committed Oct 21, 2023
1 parent bc0a03b commit 03a1b4b
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
13 changes: 13 additions & 0 deletions pkg/util/cache/lruexpirecache.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,19 @@ func (c *LRUExpireCache) Remove(key interface{}) {
delete(c.entries, key)
}

// RemoveAll removes all keys that match predicate.
func (c *LRUExpireCache) RemoveAll(predicate func(key any) bool) {
c.lock.Lock()
defer c.lock.Unlock()

for key, element := range c.entries {
if predicate(key) {
c.evictionList.Remove(element)
delete(c.entries, key)
}
}
}

// Keys returns all unexpired keys in the cache.
//
// Keep in mind that subsequent calls to Get() for any of the returned keys
Expand Down
14 changes: 14 additions & 0 deletions pkg/util/cache/lruexpirecache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,20 @@ func TestSimpleRemove(t *testing.T) {
expectNotEntry(t, c, "long-lived")
}

func TestSimpleRemoveAll(t *testing.T) {
c := NewLRUExpireCache(10)
c.Add("long-lived", "12345", 10*time.Hour)
c.Add("other-long-lived", "12345", 10*time.Hour)
c.RemoveAll(func(k any) bool {
return k.(string) == "long-lived"
})

assertKeys(t, c.Keys(), []any{"other-long-lived"})

expectNotEntry(t, c, "long-lived")
expectEntry(t, c, "other-long-lived", "12345")
}

func TestExpiredGet(t *testing.T) {
fakeClock := testingclock.NewFakeClock(time.Now())
c := NewLRUExpireCacheWithClock(10, fakeClock)
Expand Down

0 comments on commit 03a1b4b

Please sign in to comment.