Skip to content

Commit

Permalink
Merge pull request #11 from mrobinsn/master
Browse files Browse the repository at this point in the history
Bug Fix: TTL at Capacity
  • Loading branch information
Bob Uhl authored Aug 27, 2020
2 parents 37b1dce + 7aeaac2 commit d627347
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
5 changes: 5 additions & 0 deletions ttlru.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,11 @@ func (c *cache) removeEntry(e *entry) {
heap.Remove(c.heap, e.index)
}

// if a ttl was set, stop the timer to avoid leaking timers
if e.timer != nil {
e.timer.Stop()
}

// delete the item from the map
delete(c.items, e.key)
}
Expand Down
23 changes: 23 additions & 0 deletions ttlru_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,3 +223,26 @@ func TestPopEmptyHeap(t *testing.T) {

heap.Pop(&h)
}

func TestFullCacheTTLEviction(t *testing.T) {
// Test that when an item with TTL is evicted, the TTL timer is cancelled
// Otherwise, the key will be deleted earlier than it should
l := New(5, WithTTL(1*time.Second))

for i := 0; i < 6; i++ {
l.Set(i, "test")
if i == 0 {
time.Sleep(500 * time.Millisecond)
}
}

// 0 should have been evicted
_, ok := l.Get(0)
require.False(t, ok)
// add 0 back in
l.Set(0, "test")
time.Sleep(500 * time.Millisecond)
// 0 should still be there
_, ok = l.Get(0)
require.True(t, ok)
}

0 comments on commit d627347

Please sign in to comment.