From 70a628b40aefc92ccfbc1000c67ea33435835436 Mon Sep 17 00:00:00 2001 From: Cem Sancak Date: Wed, 6 Oct 2021 12:32:13 +0300 Subject: [PATCH] add flush expires on close --- niftycache.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/niftycache.go b/niftycache.go index 74e5d8f..275bd81 100644 --- a/niftycache.go +++ b/niftycache.go @@ -13,6 +13,7 @@ type Cache struct { setCB callback expireCB callback extendTTL bool + flushExpires bool items map[string]*item ih *itemsHeap m *sync.Mutex @@ -64,6 +65,12 @@ func ExtendTTLOnHit() Option { } } +func FlushExpiresOnClose() Option { + return func(nc *Cache) { + nc.flushExpires = true + } +} + func MaxExpires(maxExpires int) Option { return func(nc *Cache) { nc.maxExpires = maxExpires @@ -149,6 +156,17 @@ func (nc *Cache) handleExpirations() { select { case <-nc.done: t.Stop() + if nc.flushExpires { + nc.m.Lock() + for item := nc.ih.peek(); item != nil; item = nc.ih.peek() { + delete(nc.items, item.key) + nc.ih.pop() + if nc.expireCB != nil { + nc.callbacks.Add(nc.expireCB(item.key, item.value)) + } + } + nc.m.Unlock() + } nc.wg1.Done() return case <-t.C: