freelru: purge all expired items

This commit is contained in:
世界 2024-11-30 16:06:50 +08:00
parent 39040e06dc
commit 3f30aaf25e
No known key found for this signature in database
GPG key ID: CD109927C34A63C4
2 changed files with 16 additions and 16 deletions

View file

@ -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
}
}

View file

@ -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")
@ -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")
@ -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())
}