Reduce lock contention in Cache.WriteMulti

A write-lock was taken the whole time, but we only need the write
lock at the end.
pull/5445/head
Jason Wilder 2016-01-25 16:46:14 -07:00
parent 5bee8880db
commit 372302bcbd
1 changed files with 5 additions and 3 deletions

View File

@ -103,24 +103,26 @@ func (c *Cache) Write(key string, values []Value) error {
// WriteMulti writes the map of keys and associated values to the cache. This function is goroutine-safe.
// It returns an error if the cache has exceeded its max size.
func (c *Cache) WriteMulti(values map[string][]Value) error {
c.mu.Lock()
defer c.mu.Unlock()
totalSz := 0
for _, v := range values {
totalSz += Values(v).Size()
}
// Enough room in the cache?
c.mu.RLock()
newSize := c.size + uint64(totalSz)
if c.maxSize > 0 && newSize+c.snapshotsSize > c.maxSize {
c.mu.RUnlock()
return ErrCacheMemoryExceeded
}
c.mu.RUnlock()
c.mu.Lock()
for k, v := range values {
c.write(k, v)
}
c.size = newSize
c.mu.Unlock()
return nil
}