Skip to content

Commit

Permalink
freelru: purge all expired items
Browse files Browse the repository at this point in the history
  • Loading branch information
nekohasekai committed Nov 30, 2024
1 parent 39040e0 commit 3f30aaf
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 16 deletions.
13 changes: 9 additions & 4 deletions contrab/freelru/lru.go
Original file line number Diff line number Diff line change
Expand Up @@ -688,14 +688,19 @@ func (lru *LRU[K, V]) Purge() {
// The evict function is called for each expired item.
func (lru *LRU[K, V]) PurgeExpired() {
l := lru.len
if l == 0 {
return
}
n := now()
pos := lru.head
for i := uint32(0); i < l; i++ {
pos := lru.elements[lru.head].next
next := lru.elements[pos].next
if lru.elements[pos].expire != 0 {
if lru.elements[pos].expire > now() {
return // no more expired items
if lru.elements[pos].expire <= n {
lru.removeAt(pos)
}
lru.removeAt(pos)
}
pos = next
}
}

Expand Down
19 changes: 7 additions & 12 deletions contrab/freelru/lru_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,9 @@ func TestUpdateLifetimeOnGet(t *testing.T) {
t.Parallel()
lru, err := freelru.New[string, string](1024, maphash.NewHasher[string]().Hash32)
require.NoError(t, err)
lru.SetUpdateLifetimeOnGet(true)
lru.AddWithLifetime("hello", "world", 2*time.Second)
time.Sleep(time.Second)
_, ok := lru.Get("hello")
_, ok := lru.GetAndRefresh("hello")
require.True(t, ok)
time.Sleep(time.Second + time.Millisecond*100)
_, ok = lru.Get("hello")
Expand All @@ -28,7 +27,6 @@ func TestUpdateLifetimeOnGet1(t *testing.T) {
t.Parallel()
lru, err := freelru.New[string, string](1024, maphash.NewHasher[string]().Hash32)
require.NoError(t, err)
lru.SetUpdateLifetimeOnGet(true)
lru.AddWithLifetime("hello", "world", 2*time.Second)
time.Sleep(time.Second)
lru.Peek("hello")
Expand Down Expand Up @@ -82,14 +80,11 @@ func TestPeekWithLifetime(t *testing.T) {
lru, err := freelru.New[string, string](1024, maphash.NewHasher[string]().Hash32)
require.NoError(t, err)
lru.SetLifetime(time.Second)
lru.Add("1", "")
time.Sleep(300 * time.Millisecond)
lru.Add("2", "")
time.Sleep(300 * time.Millisecond)
lru.Add("3", "")
time.Sleep(300 * time.Millisecond)
lru.Add("4", "")
time.Sleep(time.Second)
lru.AddWithLifetime("hello", "world", 10*time.Second)
lru.Add("hello1", "")
lru.Add("hello2", "")
lru.Add("hello3", "")
time.Sleep(2 * time.Second)
lru.PurgeExpired()
require.Equal(t, 0, lru.Len())
require.Equal(t, 1, lru.Len())
}

0 comments on commit 3f30aaf

Please sign in to comment.