diff --git a/cache.go b/cache.go index db88d2f..84b9877 100644 --- a/cache.go +++ b/cache.go @@ -1063,9 +1063,18 @@ func (c *cache) ItemCount() int { // Delete all items from the cache. func (c *cache) Flush() { + var oldCache map[string]Item + c.mu.Lock() + if c.onEvicted != nil { + oldCache = c.items + } c.items = map[string]Item{} c.mu.Unlock() + + for k, v := range oldCache { + c.onEvicted(k, v.Object) + } } type janitor struct { diff --git a/cache_test.go b/cache_test.go index de3e9d6..322da59 100644 --- a/cache_test.go +++ b/cache_test.go @@ -1179,6 +1179,23 @@ func TestFlush(t *testing.T) { if x != nil { t.Error("x is not nil:", x) } + + evictMask := 0 + tc.OnEvicted(func(k string, v interface{}) { + if k == "foo" && v.(string) == "bar" { + evictMask |= 0x1 + } + if k == "baz" && v.(string) == "yes" { + evictMask |= 0x2 + } + }) + tc.Set("foo", "bar", DefaultExpiration) + tc.Set("baz", "yes", DefaultExpiration) + tc.Flush() + + if evictMask != 0x3 { + t.Error("on evicted on flush fails") + } } func TestIncrementOverflowInt(t *testing.T) {