-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple_mempool.go
60 lines (53 loc) · 1.16 KB
/
simple_mempool.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
package toolkit
import (
"sync"
"time"
)
type memo struct {
Timeout time.Time
Result interface{}
}
type MemoPool struct {
pool map[string]*memo
mutex *sync.RWMutex
}
func NewSimpleMemoPool() *MemoPool {
return &MemoPool{pool: map[string]*memo{}, mutex: new(sync.RWMutex)}
}
// memorize result return from caller() block, timeout in N seconds
func (mp *MemoPool) Memoize(key string, caller func() interface{}, timeout uint) interface{} {
if timeout == 0 {
// do not memoize
return caller()
}
mp.mutex.RLock()
memoized := mp.pool[key]
mp.mutex.RUnlock()
// reached timeout or not memoized
if memoized == nil || memoized.Timeout.Before(time.Now()) {
result := caller()
if result != nil {
duration := time.Duration(timeout) * time.Second
mp.mutex.Lock()
mp.pool[key] = &memo{
Timeout: time.Now().Add(duration),
Result: result,
}
mp.mutex.Unlock()
}
return result
}
return memoized.Result
}
func (mp *MemoPool) UnMemoize(key string) {
mp.mutex.Lock()
delete(mp.pool, key)
mp.mutex.Unlock()
}
func (mp *MemoPool) UnMemoizeAll() {
mp.mutex.Lock()
for key, _ := range mp.pool {
delete(mp.pool, key)
}
mp.mutex.Unlock()
}