-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathttlmap.go
88 lines (76 loc) · 1.6 KB
/
ttlmap.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package ttlmap
import (
"sync"
"time"
)
// TtlMap is a synchronised map of items that auto-expire once stale
type TtlMap struct {
mutex sync.RWMutex
ttl time.Duration
items map[interface{}]*Item
}
// Set is a thread-safe way to add new items to the map
func (t *TtlMap) Set(key interface{}, data interface{}) {
t.mutex.Lock()
defer t.mutex.Unlock()
item := &Item{data: data}
item.touch(t.ttl)
t.items[key] = item
}
// Get is a thread-safe way to lookup items
// Every lookup, also touches the item, hence extending it's life
func (t *TtlMap) Get(key interface{}) (data interface{}, found bool) {
t.mutex.Lock()
defer t.mutex.Unlock()
item, exists := t.items[key]
if !exists || item.expired() {
data = ""
found = false
} else {
item.touch(t.ttl)
data = item.data
found = true
}
return
}
// Count returns the number of items in the cache
// (helpful for tracking memory leaks)
func (t *TtlMap) Count() int {
t.mutex.RLock()
defer t.mutex.RUnlock()
count := len(t.items)
return count
}
func (t *TtlMap) cleanup() {
t.mutex.Lock()
defer t.mutex.Unlock()
for key, item := range t.items {
if item.expired() {
delete(t.items, key)
}
}
}
func (t *TtlMap) startCleanupTimer() {
duration := t.ttl
if duration < time.Second {
duration = time.Second
}
ticker := time.Tick(duration)
go (func() {
for {
select {
case <-ticker:
t.cleanup()
}
}
})()
}
// NewTtlMap is a helper to create instance of the Map struct
func NewTtlMap(duration time.Duration) *TtlMap {
t := &TtlMap{
ttl: duration,
items: map[interface{}]*Item{},
}
t.startCleanupTimer()
return t
}