Make Items() return a copy rather than an unsynchronized reference to the underlying items map

This commit is contained in:
Patrick Mylund Nielsen 2016-11-25 13:56:11 -05:00
parent 1881a9bccb
commit a2d8b56f0c
1 changed files with 13 additions and 7 deletions

View File

@ -998,19 +998,25 @@ func (c *cache) LoadFile(fname string) error {
return fp.Close() return fp.Close()
} }
// Returns the items in the cache. This may include items that have expired, // Copies all unexpired items in the cache into a new map and returns it.
// but have not yet been cleaned up. If this is significant, the Expiration
// fields of the items should be checked. Note that explicit synchronization
// is needed to use a cache and its corresponding Items() return value at
// the same time, as the map is shared.
func (c *cache) Items() map[string]Item { func (c *cache) Items() map[string]Item {
c.mu.RLock() c.mu.RLock()
defer c.mu.RUnlock() defer c.mu.RUnlock()
return c.items m := make(map[string]Item, len(c.items))
now := time.Now().UnixNano()
for k, v := range c.items {
if v.Expiration > 0 {
if now > v.Expiration {
continue
}
}
m[k] = v
}
return m
} }
// Returns the number of items in the cache. This may include items that have // Returns the number of items in the cache. This may include items that have
// expired, but have not yet been cleaned up. Equivalent to len(c.Items()). // expired, but have not yet been cleaned up.
func (c *cache) ItemCount() int { func (c *cache) ItemCount() int {
c.mu.RLock() c.mu.RLock()
n := len(c.items) n := len(c.items)