-
Notifications
You must be signed in to change notification settings - Fork 29
/
evict.go
68 lines (58 loc) · 1.2 KB
/
evict.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
package flashdb
import (
"math/rand"
"runtime"
"time"
"github.com/arriqaaq/hash"
)
const (
MinimumStartupTime = 500 * time.Millisecond
MaximumStartupTime = 2 * MinimumStartupTime
)
// Used to put a random delay before start of each shard, so as to not
// let various shards lock at the same time
func startupDelay() time.Duration {
rand := rand.New(rand.NewSource(time.Now().UnixNano()))
d, delta := MinimumStartupTime, (MaximumStartupTime - MinimumStartupTime)
if delta > 0 {
d += time.Duration(rand.Int63n(int64(delta)))
}
return d
}
type evictor interface {
run(cache *hash.Hash)
stop()
}
func newSweeperWithStore(s store, sweepTime time.Duration) evictor {
var swp = &sweeper{
interval: sweepTime,
stopC: make(chan bool),
store: s,
}
runtime.SetFinalizer(swp, stopSweeper)
return swp
}
func stopSweeper(c evictor) {
c.stop()
}
type sweeper struct {
store store
interval time.Duration
stopC chan bool
}
func (s *sweeper) run(cache *hash.Hash) {
<-time.After(startupDelay())
ticker := time.NewTicker(s.interval)
for {
select {
case <-ticker.C:
s.store.evict(cache)
case <-s.stopC:
ticker.Stop()
return
}
}
}
func (s *sweeper) stop() {
s.stopC <- true
}