/
concurrent_lru.go
62 lines (52 loc) · 1.23 KB
/
concurrent_lru.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package common
import (
"sync"
"github.com/golang/groupcache/lru"
)
// Cache is an LRU cache. It is safe for concurrent access.
type Cache struct {
cache *lru.Cache
sync.RWMutex
}
// NewCache creates a new Cache.
// If maxEntries is zero, the cache has no limit and it's assumed
// that eviction is done by the caller.
func NewCache(maxEntries int) *Cache {
return &Cache{cache: lru.New(maxEntries)}
}
// Add adds a value to the cache.
func (c *Cache) Add(key, value interface{}) {
c.Lock()
defer c.Unlock()
c.cache.Add(key, value)
}
// Get looks up a key's value from the cache.
func (c *Cache) Get(key interface{}) (value interface{}, ok bool) {
c.Lock()
defer c.Unlock()
return c.cache.Get(key)
}
// Remove removes the provided key from the cache.
func (c *Cache) Remove(key interface{}) {
c.Lock()
defer c.Unlock()
c.cache.Remove(key)
}
// RemoveOldest removes the oldest item from the cache.
func (c *Cache) RemoveOldest() {
c.Lock()
defer c.Unlock()
c.cache.RemoveOldest()
}
// Len returns the number of items in the cache.
func (c *Cache) Len() int {
c.RLock()
defer c.RUnlock()
return c.cache.Len()
}
// Clear purges all stored items from the cache.
func (c *Cache) Clear() {
c.Lock()
defer c.Unlock()
c.cache.Clear()
}