Skip to content

Commit

Permalink
Remove key from policy after TTL eviction (#130)
Browse files Browse the repository at this point in the history
  • Loading branch information
ldechoux authored Jan 30, 2020
1 parent 2dd5ff5 commit ff325ad
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
41 changes: 41 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,47 @@ func TestCacheSet(t *testing.T) {
require.False(t, c.Set(1, 1, 1))
}

func TestRecacheWithTTL(t *testing.T) {
c, err := NewCache(&Config{
NumCounters: 100,
MaxCost: 10,
BufferItems: 64,
Metrics: true,
})

require.NoError(t, err)

// Set initial value for key = 1
insert := c.SetWithTTL(1, 1, 1, 5*time.Second)
require.True(t, insert)
time.Sleep(2 * time.Second)

// Get value from cache for key = 1
val, ok := c.Get(1)
require.True(t, ok)
require.NotNil(t, val)
require.Equal(t, 1, val)

// Wait for expiration
time.Sleep(5 * time.Second)

// The cached value for key = 1 should be gone
val, ok = c.Get(1)
require.False(t, ok)
require.Nil(t, val)

// Set new value for key = 1
insert = c.SetWithTTL(1, 2, 1, 5*time.Second)
require.True(t, insert)
time.Sleep(2 * time.Second)

// Get value from cache for key = 1
val, ok = c.Get(1)
require.True(t, ok)
require.NotNil(t, val)
require.Equal(t, 2, val)
}

func TestCacheSetWithTTL(t *testing.T) {
m := &sync.Mutex{}
evicted := make(map[uint64]struct{})
Expand Down
4 changes: 3 additions & 1 deletion ttl.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,10 @@ func (m *expirationMap) cleanup(store store, policy policy, onEvict onEvictFunc)
continue
}

_, value := store.Del(key, conflict)
cost := policy.Cost(key)
policy.Del(key)
_, value := store.Del(key, conflict)

if onEvict != nil {
onEvict(key, conflict, value, cost)
}
Expand Down

0 comments on commit ff325ad

Please sign in to comment.