From 3fa767d9ffa9cc9bcdfecbe97c046fa1077d7a60 Mon Sep 17 00:00:00 2001 From: Karl Seguin Date: Thu, 31 Oct 2013 11:45:22 +0800 Subject: [PATCH] added non-threadsafe Clear (for tests), fixed Fetch --- bucket.go | 6 ++++++ cache.go | 22 ++++++++++++++++------ 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/bucket.go b/bucket.go index 43e4973..81ab787 100755 --- a/bucket.go +++ b/bucket.go @@ -45,3 +45,9 @@ func (b *Bucket) getAndDelete(key string) *Item{ delete(b.lookup, key) return item } + +func (b *Bucket) clear() { + b.Lock() + defer b.Unlock() + b.lookup = make(map[string]*Item) +} diff --git a/cache.go b/cache.go index ccb15c5..c4284ae 100755 --- a/cache.go +++ b/cache.go @@ -18,7 +18,7 @@ type Cache struct { func New(config *Configuration) *Cache { c := &Cache{ - list: new(list.List), + list: list.New(), Configuration: config, bucketCount: uint32(config.buckets), buckets: make([]*Bucket, config.buckets), @@ -51,12 +51,14 @@ func (c *Cache) Set(key string, value interface{}, duration time.Duration) { c.promote(item) } -func (c *Cache) Fetch(key string, duration time.Duration, fetch func() interface{}) interface{} { +func (c *Cache) Fetch(key string, duration time.Duration, fetch func() (interface{}, error)) (interface{}, error) { item := c.Get(key) - if item != nil { return item } - value := fetch() - c.Set(key, value, duration) - return value + if item != nil { return item, nil } + value, err := fetch() + if err == nil { + c.Set(key, value, duration) + } + return value, err } func (c *Cache) Delete(key string) { @@ -66,6 +68,14 @@ func (c *Cache) Delete(key string) { } } +//this isn't thread safe. It's meant to be called from non-concurrent tests +func (c *Cache) Clear() { + for _, bucket := range c.buckets { + bucket.clear() + } + c.list = list.New() +} + func (c *Cache) deleteItem(bucket *Bucket, item *Item) { bucket.delete(item.key) //stop othe GETs from getting it c.deletables <- item