OSDN Git Service

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