forked from karlseguin/rcache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
intcache.go
135 lines (121 loc) · 2.22 KB
/
intcache.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package rcache
import (
"sync"
"time"
)
type IntFetcher func(key int) interface{}
type IntCache struct {
sync.RWMutex
fetcher IntFetcher
ttl time.Duration
items map[int]*Item
fetchingLock sync.Mutex
fetchings map[int]time.Time
}
func NewInt(fetcher IntFetcher, ttl time.Duration) *IntCache {
c := &IntCache{
ttl: ttl,
fetcher: fetcher,
items: make(map[int]*Item),
fetchings: make(map[int]time.Time),
}
go c.reaper()
return c
}
func (c *IntCache) Get(key int) interface{} {
c.RLock()
item, exists := c.items[key]
c.RUnlock()
if exists == false {
return c.fetch(key)
}
state := item.State()
if state == expired {
return c.fetch(key)
}
if state == stale {
go c.cfetch(key)
}
return item.value
}
func (c *IntCache) Replace(key int, value interface{}) {
c.RLock()
_, exists := c.items[key]
c.RUnlock()
if exists == false {
return
}
c.Set(key, value)
}
func (c *IntCache) Delete(key int) {
c.Lock()
delete(c.items, key)
c.Unlock()
}
func (c *IntCache) Clear() {
c.Lock()
c.items = make(map[int]*Item)
c.Unlock()
}
func (c *IntCache) fetch(key int) interface{} {
value := c.fetcher(key)
if value == nil {
return nil
}
c.Set(key, value)
return value
}
func (c *IntCache) cfetch(key int) {
now := time.Now()
c.fetchingLock.Lock()
start, exists := c.fetchings[key]
if exists && start.Add(FETCH_TIME_LIMIT).Before(now) {
c.fetchingLock.Unlock()
return
}
c.fetchings[key] = now
c.fetchingLock.Unlock()
c.fetch(key)
c.fetchingLock.Lock()
delete(c.fetchings, key)
c.fetchingLock.Unlock()
}
func (c *IntCache) reaper() {
scratch := make([]int, REAPER_LIMIT)
for {
time.Sleep(REAPER_FREQUENCY)
c.reap(scratch)
}
}
func (c *IntCache) Set(key int, value interface{}) {
item := &Item{
value: value,
expires: time.Now().Add(c.ttl),
}
c.Lock()
c.items[key] = item
c.Unlock()
}
func (c *IntCache) reap(scratch []int) {
count, victims := 0, 0
c.RLock()
for key, item := range c.items {
if item.State() == expired {
scratch[victims] = key
victims++
}
count++
if count == REAPER_LIMIT {
break
}
}
c.RUnlock()
if victims == 0 {
return
}
c.Lock()
defer c.Unlock()
for i := 0; i < victims; i++ {
delete(c.items, scratch[i])
}
}