diff options
author | Martin Polden <mpolden@mpolden.no> | 2019-12-28 13:53:16 +0100 |
---|---|---|
committer | Martin Polden <mpolden@mpolden.no> | 2019-12-28 13:54:11 +0100 |
commit | 48d335f181dd10465d217102c751cc62188d6739 (patch) | |
tree | 9106932b1db26aa3e7743634185724a236f1f1e7 | |
parent | 04880e684d78256cd8705f77db0cc75e4c1de83e (diff) |
Simplify cache maintenance
-rw-r--r-- | cache/cache.go | 59 | ||||
-rw-r--r-- | cache/cache_test.go | 9 |
2 files changed, 30 insertions, 38 deletions
diff --git a/cache/cache.go b/cache/cache.go index 0702b1a..8390420 100644 --- a/cache/cache.go +++ b/cache/cache.go @@ -11,42 +11,12 @@ import ( // Cache represents a cache of DNS responses. Use New to initialize a new cache. type Cache struct { - capacity int - now func() time.Time - maintainer *maintainer - mu sync.RWMutex - wg sync.WaitGroup - values map[uint64]*Value - keys []uint64 -} - -type maintainer struct { - interval time.Duration + capacity int + values map[uint64]*Value + keys []uint64 + mu sync.RWMutex done chan bool -} - -func maintain(cache *Cache, interval time.Duration) { - m := &maintainer{ - interval: interval, - done: make(chan bool), - } - cache.maintainer = m - cache.wg.Add(1) - go m.run(cache) -} - -func (m *maintainer) run(cache *Cache) { - defer cache.wg.Done() - ticker := time.NewTicker(m.interval) - for { - select { - case <-ticker.C: - cache.deleteExpired() - case <-m.done: - ticker.Stop() - return - } - } + now func() time.Time } // Value represents a value stored in the cache. @@ -97,8 +67,9 @@ func New(capacity int, expiryInterval time.Duration) *Cache { now: time.Now, capacity: capacity, values: make(map[uint64]*Value, capacity), + done: make(chan bool), } - maintain(cache, expiryInterval) + go maintain(cache, expiryInterval) return cache } @@ -111,10 +82,22 @@ func NewKey(name string, qtype, qclass uint16) uint64 { return h.Sum64() } +func maintain(cache *Cache, interval time.Duration) { + ticker := time.NewTicker(interval) + for { + select { + case <-cache.done: + ticker.Stop() + return + case <-ticker.C: + cache.deleteExpired() + } + } +} + // Close closes the cache. func (c *Cache) Close() error { - c.maintainer.done <- true - c.wg.Wait() + c.done <- true return nil } diff --git a/cache/cache_test.go b/cache/cache_test.go index 2629429..5b08246 100644 --- a/cache/cache_test.go +++ b/cache/cache_test.go @@ -211,3 +211,12 @@ func BenchmarkCache(b *testing.B) { c.Get(uint64(n)) } } + +func BenchmarkCacheEviction(b *testing.B) { + c := New(1, time.Second) + b.ResetTimer() + for n := 0; n < b.N; n++ { + c.Set(uint64(n), &dns.Msg{}) + c.Get(uint64(n)) + } +} |