-
Notifications
You must be signed in to change notification settings - Fork 4
/
map_hoard.go
93 lines (84 loc) · 1.75 KB
/
map_hoard.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
89
90
91
92
93
package ssp
import (
"fmt"
"sync"
"time"
)
type valExpire struct {
value *HoardCache
expiration time.Time
}
func (ve valExpire) Expired() bool {
return ve.expiration.Before(time.Now())
}
// MapHoard implements a Hoard that is backed by an in-memory map
type MapHoard struct {
cache map[Nut]*valExpire
mutex *sync.Mutex
}
// NewMapHoard creates a new MapHoard
func NewMapHoard() *MapHoard {
mh := &MapHoard{
cache: make(map[Nut]*valExpire),
mutex: &sync.Mutex{},
}
go mh.cleaner()
return mh
}
func (mh *MapHoard) cleaner() {
ticker := time.NewTicker(100 * time.Millisecond)
for start := range ticker.C {
mh.mutex.Lock()
i := 0
for k, v := range mh.cache {
if v.Expired() {
delete(mh.cache, k)
}
i++
// check for going over time
if i%100 == 0 {
if time.Now().Sub(start) > 50*time.Millisecond {
break
}
}
}
mh.mutex.Unlock()
}
}
// Get implements Hoard
func (mh *MapHoard) Get(nut Nut) (*HoardCache, error) {
mh.mutex.Lock()
defer mh.mutex.Unlock()
if value, ok := mh.cache[nut]; ok {
if !value.Expired() {
return value.value, nil
}
delete(mh.cache, nut)
}
return nil, ErrNotFound
}
// GetAndDelete implements Hoard
func (mh *MapHoard) GetAndDelete(nut Nut) (*HoardCache, error) {
mh.mutex.Lock()
defer mh.mutex.Unlock()
if value, ok := mh.cache[nut]; ok {
delete(mh.cache, nut)
if !value.Expired() {
return value.value, nil
}
}
return nil, ErrNotFound
}
// Save implements Hoard
func (mh *MapHoard) Save(nut Nut, value *HoardCache, expiration time.Duration) error {
if nut == "" {
return fmt.Errorf("empty nuts are not allowed")
}
mh.mutex.Lock()
defer mh.mutex.Unlock()
mh.cache[nut] = &valExpire{
value: value,
expiration: time.Now().Add(expiration),
}
return nil
}