-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconcurrentcache.go
More file actions
78 lines (67 loc) · 1.38 KB
/
concurrentcache.go
File metadata and controls
78 lines (67 loc) · 1.38 KB
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
package concurrentcache
import (
"sync"
"time"
)
type Locker interface {
RLock()
TryRLock() bool
RUnlock()
Lock()
TryLock() bool
Unlock()
RLocker() sync.Locker
}
type ConcurrentCache[T any] interface {
Close()
Access(callback func(locker Locker, cache T))
AccessRead(callback func(cache T))
AccessWrite(callback func(cache T))
}
type concurrentCache[T any] struct {
sync.RWMutex
stopChan chan struct{}
wg sync.WaitGroup
cache T
update func(locker Locker, cache T)
}
func NewConcurrentCache[T any](cache T, updateInterval time.Duration, update func(locker Locker, cache T)) ConcurrentCache[T] {
c := &concurrentCache[T]{
RWMutex: sync.RWMutex{},
stopChan: make(chan struct{}),
wg: sync.WaitGroup{},
cache: cache,
update: update,
}
c.wg.Add(1)
go func() {
defer c.wg.Done()
ticker := time.NewTicker(updateInterval)
for {
select {
case <-ticker.C:
c.update(c, c.cache)
case <-c.stopChan:
return
}
}
}()
return c
}
func (c *concurrentCache[T]) Close() {
close(c.stopChan)
c.wg.Wait()
}
func (c *concurrentCache[T]) Access(callback func(locker Locker, cache T)) {
callback(c, c.cache)
}
func (c *concurrentCache[T]) AccessRead(callback func(cache T)) {
c.RLock()
defer c.RUnlock()
callback(c.cache)
}
func (c *concurrentCache[T]) AccessWrite(callback func(cache T)) {
c.Lock()
defer c.Unlock()
callback(c.cache)
}