-
Notifications
You must be signed in to change notification settings - Fork 0
/
concurrentShardedCounts.go
executable file
·71 lines (56 loc) · 1.59 KB
/
concurrentShardedCounts.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
package counting
import (
"fmt"
"sort"
"strings"
"sync"
)
var _ Counts = (*ConcurrentShardedCounts)(nil)
// ConcurrentShardedCounts keeps counts for a sharded data structure
// This implementation is concurrently safe
type ConcurrentShardedCounts struct {
mutex sync.RWMutex
byShard map[string]int64
}
// NewConcurrentShardedCounts creates a new ConcurrentShardedCounts
func NewConcurrentShardedCounts() *ConcurrentShardedCounts {
return &ConcurrentShardedCounts{
byShard: make(map[string]int64),
}
}
// PutCounts registers counts for a shard
func (counts *ConcurrentShardedCounts) PutCounts(shardName string, value int64) {
counts.mutex.Lock()
counts.byShard[shardName] = value
counts.mutex.Unlock()
}
// GetTotal gets total count
func (counts *ConcurrentShardedCounts) GetTotal() int64 {
counts.mutex.RLock()
defer counts.mutex.RUnlock()
total := int64(0)
for _, count := range counts.byShard {
total += count
}
return total
}
func (counts *ConcurrentShardedCounts) String() string {
var builder strings.Builder
_, _ = fmt.Fprintf(&builder, "Total:%d; ", counts.GetTotal())
counts.mutex.RLock()
defer counts.mutex.RUnlock()
// First, we sort the keys alphanumerically
keys := make([]string, 0, len(counts.byShard))
for key := range counts.byShard {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
_, _ = fmt.Fprintf(&builder, "[%s]=%d; ", key, counts.byShard[key])
}
return builder.String()
}
// IsInterfaceNil returns true if there is no value under the interface
func (counts *ConcurrentShardedCounts) IsInterfaceNil() bool {
return counts == nil
}