-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache_cleaner.go
77 lines (65 loc) · 1.31 KB
/
cache_cleaner.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
package cache
import (
"time"
csmap "github.com/mhmtszr/concurrent-swiss-map"
)
type mockCleaner struct {
started bool
stopped bool
}
func (c *mockCleaner) Start() {
c.started = true
}
func (c *mockCleaner) Stop() {
c.stopped = true
}
type cleaner[K comparable, V any] interface {
// Start cleaning at intervals.
Start()
// Stop cleaning.
Stop()
}
type cacheCleaner[K comparable, V any] struct {
data *csmap.CsMap[K, *entry[K, V]]
cleanupInterval time.Duration
donechn chan (struct{})
}
func newCacheCleaner[K comparable, V any](
data *csmap.CsMap[K, *entry[K, V]],
cleanupInterval time.Duration,
) cleaner[K, V] {
return &cacheCleaner[K, V]{
data: data,
cleanupInterval: cleanupInterval,
donechn: make(chan struct{}),
}
}
func (c *cacheCleaner[K, V]) Start() {
go func() {
ticker := time.NewTicker(c.cleanupInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
c.cleanup()
case <-c.donechn:
return
}
}
}()
}
func (c *cacheCleaner[K, V]) Stop() {
c.donechn <- struct{}{}
}
func (c *cacheCleaner[K, V]) cleanup() {
keys := make([]K, 0)
c.data.Range(func(key K, entry *entry[K, V]) (stop bool) {
if entry.isExpired() {
keys = append(keys, key)
}
return false
})
for _, key := range keys {
c.data.Delete(key)
}
}