Skip to content

Commit a2d8b56

Browse files
committed
Make Items() return a copy rather than an unsynchronized reference to the underlying items map
1 parent 1881a9b commit a2d8b56

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

cache.go

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -998,19 +998,25 @@ func (c *cache) LoadFile(fname string) error {
998998
return fp.Close()
999999
}
10001000

1001-
// Returns the items in the cache. This may include items that have expired,
1002-
// but have not yet been cleaned up. If this is significant, the Expiration
1003-
// fields of the items should be checked. Note that explicit synchronization
1004-
// is needed to use a cache and its corresponding Items() return value at
1005-
// the same time, as the map is shared.
1001+
// Copies all unexpired items in the cache into a new map and returns it.
10061002
func (c *cache) Items() map[string]Item {
10071003
c.mu.RLock()
10081004
defer c.mu.RUnlock()
1009-
return c.items
1005+
m := make(map[string]Item, len(c.items))
1006+
now := time.Now().UnixNano()
1007+
for k, v := range c.items {
1008+
if v.Expiration > 0 {
1009+
if now > v.Expiration {
1010+
continue
1011+
}
1012+
}
1013+
m[k] = v
1014+
}
1015+
return m
10101016
}
10111017

10121018
// Returns the number of items in the cache. This may include items that have
1013-
// expired, but have not yet been cleaned up. Equivalent to len(c.Items()).
1019+
// expired, but have not yet been cleaned up.
10141020
func (c *cache) ItemCount() int {
10151021
c.mu.RLock()
10161022
n := len(c.items)

0 commit comments

Comments
 (0)