Debian Codegraph @

pkg/sievecache/sync.go

raw symbols SCIP
1 package sievecache
2
3 import (
4 "reflect"
5 "sync"
6 )
7
8 // SyncSieveCache is a thread-safe wrapper around SieveCache.
9 // It provides the same functionality but with thread safety guarantees.
10 type SyncSieveCache[K comparable, V any] struct {
11 cache *SieveCache[K, V]
12 mutex sync.RWMutex
13 }
14
15 // NewSync creates a new thread-safe cache with the given capacity.
16 func NewSync[K comparable, V any](capacity int) (*SyncSieveCache[K, V], error) {
17 cache, err := New[K, V](capacity)
18 if err != nil {
19 return nil, err
20 }
21
22 return &SyncSieveCache[K, V]{
23 cache: cache,
24 mutex: sync.RWMutex{},
25 }, nil
26 }
27
28 // DefaultSync creates a new thread-safe cache with a default capacity of 100.
29 func DefaultSync[K comparable, V any]() *SyncSieveCache[K, V] {
30 cache, err := NewSync[K, V](100)
31 if err != nil {
32 // This should never happen with non-zero capacity
33 panic("Failed to create cache with default capacity")
34 }
35 return cache
36 }
37
38 // FromSieveCache creates a new thread-safe cache from an existing SieveCache.
39 func FromSieveCache[K comparable, V any](cache *SieveCache[K, V]) *SyncSieveCache[K, V] {
40 return &SyncSieveCache[K, V]{
41 cache: cache,
42 mutex: sync.RWMutex{},
43 }
44 }
45
46 // Capacity returns the maximum number of entries the cache can hold.
47 func (c *SyncSieveCache[K, V]) Capacity() int {
48 c.mutex.RLock()
49 defer c.mutex.RUnlock()
50 return c.cache.Capacity()
51 }
52
53 // Len returns the number of cached values.
54 func (c *SyncSieveCache[K, V]) Len() int {
55 c.mutex.RLock()
56 defer c.mutex.RUnlock()
57 return c.cache.Len()
58 }
59
60 // IsEmpty returns true when no values are currently cached.
61 func (c *SyncSieveCache[K, V]) IsEmpty() bool {
62 c.mutex.RLock()
63 defer c.mutex.RUnlock()
64 return c.cache.IsEmpty()
65 }
66
67 // ContainsKey returns true if there is a value in the cache mapped to by key.
68 func (c *SyncSieveCache[K, V]) ContainsKey(key K) bool {
69 c.mutex.RLock()
70 defer c.mutex.RUnlock()
71 return c.cache.ContainsKey(key)
72 }
73
74 // Get returns the value in the cache mapped to by key.
75 // Unlike the unwrapped SieveCache, this returns a copy of the value
76 // rather than a reference, since the mutex guard is released after this method returns.
77 func (c *SyncSieveCache[K, V]) Get(key K) (V, bool) {
78 c.mutex.Lock()
79 defer c.mutex.Unlock()
80 return c.cache.Get(key)
81 }
82
83 // GetMut gets a mutable reference to the value in the cache mapped to by key via a callback function.
84 // Returns true if the key exists and the callback was invoked, false otherwise.
85 // The callback may be invoked more than once if the entry is modified concurrently;
86 // non-idempotent side effects should be avoided or guarded with WithLock instead.
87 func (c *SyncSieveCache[K, V]) GetMut(key K, f func(*V)) bool {
88 for {
89 c.mutex.Lock()
90 ptr := c.cache.GetPointer(key)
91 if ptr == nil {
92 c.mutex.Unlock()
93 return false
94 }
95 original := *ptr
96 valueCopy := original
97 c.mutex.Unlock()
98
99 f(&valueCopy)
100
101 c.mutex.Lock()
102 ptr = c.cache.GetPointer(key)
103 if ptr == nil {
104 c.mutex.Unlock()
105 return false
106 }
107 if reflect.DeepEqual(*ptr, original) {
108 *ptr = valueCopy
109 c.mutex.Unlock()
110 return true
111 }
112 c.mutex.Unlock()
113 }
114 }
115
116 // Insert maps key to value in the cache, possibly evicting old entries.
117 func (c *SyncSieveCache[K, V]) Insert(key K, value V) bool {
118 c.mutex.Lock()
119 defer c.mutex.Unlock()
120 return c.cache.Insert(key, value)
121 }
122
123 // Remove removes the cache entry mapped to by key.
124 func (c *SyncSieveCache[K, V]) Remove(key K) (V, bool) {
125 c.mutex.Lock()
126 defer c.mutex.Unlock()
127 return c.cache.Remove(key)
128 }
129
130 // Evict removes and returns a value from the cache that was not recently accessed.
131 func (c *SyncSieveCache[K, V]) Evict() (V, bool) {
132 c.mutex.Lock()
133 defer c.mutex.Unlock()
134 return c.cache.Evict()
135 }
136
137 // Clear removes all entries from the cache.
138 func (c *SyncSieveCache[K, V]) Clear() {
139 c.mutex.Lock()
140 defer c.mutex.Unlock()
141 c.cache.Clear()
142 }
143
144 // Keys returns a slice of all keys in the cache.
145 func (c *SyncSieveCache[K, V]) Keys() []K {
146 c.mutex.RLock()
147 defer c.mutex.RUnlock()
148 return c.cache.Keys()
149 }
150
151 // Values returns a slice of all values in the cache.
152 func (c *SyncSieveCache[K, V]) Values() []V {
153 c.mutex.RLock()
154 defer c.mutex.RUnlock()
155 return c.cache.Values()
156 }
157
158 // Items returns a slice of all key-value pairs in the cache.
159 func (c *SyncSieveCache[K, V]) Items() []struct {
160 Key K
161 Value V
162 } {
163 c.mutex.RLock()
164 defer c.mutex.RUnlock()
165 return c.cache.Items()
166 }
167
168 // ForEachValue applies a function to all values in the cache.
169 // The function receives and can modify a copy of each value, and changes will be saved back to the cache.
170 // Modifications are dropped for keys that were updated concurrently by another goroutine.
171 func (c *SyncSieveCache[K, V]) ForEachValue(f func(*V)) {
172 c.mutex.RLock()
173 items := c.cache.Items()
174 c.mutex.RUnlock()
175
176 updates := make([]struct {
177 key K
178 original V
179 updated V
180 }, len(items))
181 for i, item := range items {
182 updates[i].key = item.Key
183 updates[i].original = item.Value
184 updates[i].updated = item.Value
185 f(&updates[i].updated)
186 }
187
188 c.mutex.Lock()
189 defer c.mutex.Unlock()
190 for _, u := range updates {
191 ptr := c.cache.GetPointer(u.key)
192 if ptr != nil && reflect.DeepEqual(*ptr, u.original) {
193 *ptr = u.updated
194 }
195 }
196 }
197
198 // ForEachEntry applies a function to all key-value pairs in the cache.
199 // The function receives the key and can modify a copy of each value, and changes will be saved back to the cache.
200 // Modifications are dropped for keys that were updated concurrently by another goroutine.
201 func (c *SyncSieveCache[K, V]) ForEachEntry(f func(K, *V)) {
202 c.mutex.RLock()
203 items := c.cache.Items()
204 c.mutex.RUnlock()
205
206 updates := make([]struct {
207 key K
208 original V
209 updated V
210 }, len(items))
211 for i, item := range items {
212 updates[i].key = item.Key
213 updates[i].original = item.Value
214 updates[i].updated = item.Value
215 f(item.Key, &updates[i].updated)
216 }
217
218 c.mutex.Lock()
219 defer c.mutex.Unlock()
220 for _, u := range updates {
221 ptr := c.cache.GetPointer(u.key)
222 if ptr != nil && reflect.DeepEqual(*ptr, u.original) {
223 *ptr = u.updated
224 }
225 }
226 }
227
228 // WithLock gets exclusive access to the underlying cache to perform multiple operations atomically.
229 // This is useful when you need to perform a series of operations that depend on each other.
230 func (c *SyncSieveCache[K, V]) WithLock(f func(*SieveCache[K, V])) {
231 c.mutex.Lock()
232 defer c.mutex.Unlock()
233 f(c.cache)
234 }
235
236 // Retain only keeps elements specified by the predicate.
237 // Removes all entries for which f returns false.
238 func (c *SyncSieveCache[K, V]) Retain(f func(K, V) bool) {
239 // First collect all items under the read lock
240 c.mutex.RLock()
241 items := c.cache.Items()
242 c.mutex.RUnlock()
243
244 // Estimate number of elements to remove - pre-allocate with a reasonable capacity
245 estimatedRemoveCount := len(items) / 4 // Assume about 25% will be removed
246 if estimatedRemoveCount < 8 {
247 estimatedRemoveCount = 8 // Minimum size for small caches
248 }
249 if estimatedRemoveCount > 1024 {
250 estimatedRemoveCount = 1024 // Cap at reasonable maximum
251 }
252
253 // Check each entry against the predicate without holding the lock
254 keysToRemove := make([]K, 0, estimatedRemoveCount)
255 for _, item := range items {
256 if !f(item.Key, item.Value) {
257 keysToRemove = append(keysToRemove, item.Key)
258 }
259 }
260
261 // Remove entries that don't match the predicate
262 c.mutex.Lock()
263 defer c.mutex.Unlock()
264 for _, key := range keysToRemove {
265 c.cache.Remove(key)
266 }
267 }
268
269 // RetainBatch is an optimized version of Retain that collects all keys to remove first,
270 // then removes them in a single batch operation with a single lock acquisition.
271 func (c *SyncSieveCache[K, V]) RetainBatch(f func(K, V) bool) {
272 // First collect all items under the read lock
273 c.mutex.RLock()
274 items := c.cache.Items()
275 c.mutex.RUnlock()
276
277 // Estimate number of elements to remove - pre-allocate with a reasonable capacity
278 estimatedRemoveCount := len(items) / 4 // Assume about 25% will be removed
279 if estimatedRemoveCount < 8 {
280 estimatedRemoveCount = 8 // Minimum size for small caches
281 }
282 if estimatedRemoveCount > 1024 {
283 estimatedRemoveCount = 1024 // Cap at reasonable maximum
284 }
285
286 // Collect keys to remove without holding the lock
287 keysToRemove := make([]K, 0, estimatedRemoveCount)
288 for _, item := range items {
289 if !f(item.Key, item.Value) {
290 keysToRemove = append(keysToRemove, item.Key)
291 }
292 }
293
294 // If there are keys to remove, do it in a single batch operation
295 if len(keysToRemove) > 0 {
296 c.mutex.Lock()
297 defer c.mutex.Unlock()
298 for _, key := range keysToRemove {
299 c.cache.Remove(key)
300 }
301 }
302 }
303
304 // RecommendedCapacity analyzes the current cache utilization and recommends a new capacity.
305 func (c *SyncSieveCache[K, V]) RecommendedCapacity(minFactor, maxFactor, lowThreshold, highThreshold float64) int {
306 c.mutex.RLock()
307 defer c.mutex.RUnlock()
308 return c.cache.RecommendedCapacity(minFactor, maxFactor, lowThreshold, highThreshold)
309 }