Skip to content

Commit b26c342

Browse files
committed
feat: add setnx (if not exists, set kv)
Signed-off-by: rfyiamcool <rfyiamcool@163.com>
1 parent dd06719 commit b26c342

File tree

2 files changed

+15
-11
lines changed

2 files changed

+15
-11
lines changed

bucket.go

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,19 +36,27 @@ func (b *bucket[T]) get(key string) *Item[T] {
3636
}
3737

3838
func (b *bucket[T]) setnx(key string, value T, duration time.Duration, track bool) *Item[T] {
39-
b.Lock()
40-
defer b.Unlock()
41-
39+
b.RLock()
4240
item := b.lookup[key]
41+
b.RUnlock()
4342
if item != nil {
4443
return item
4544
}
4645

4746
expires := time.Now().Add(duration).UnixNano()
48-
item = newItem(key, value, expires, track)
49-
b.lookup[key] = item
47+
newItem := newItem(key, value, expires, track)
5048

51-
return item
49+
b.Lock()
50+
defer b.Unlock()
51+
52+
// check again under write lock
53+
item = b.lookup[key]
54+
if item != nil {
55+
return item
56+
}
57+
58+
b.lookup[key] = newItem
59+
return newItem
5260
}
5361

5462
func (b *bucket[T]) set(key string, value T, duration time.Duration, track bool) (*Item[T], *Item[T]) {

cache.go

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ func (c *Cache[T]) Set(key string, value T, duration time.Duration) {
148148

149149
// Setnx set the value in the cache for the specified duration if not exists
150150
func (c *Cache[T]) Setnx(key string, value T, duration time.Duration) {
151-
c.setnx(key, value, duration, false)
151+
c.bucket(key).setnx(key, value, duration, false)
152152
}
153153

154154
// Replace the value if it exists, does not set if it doesn't.
@@ -205,10 +205,6 @@ func (c *Cache[T]) set(key string, value T, duration time.Duration, track bool)
205205
return item
206206
}
207207

208-
func (c *Cache[T]) setnx(key string, value T, duration time.Duration, track bool) *Item[T] {
209-
return c.bucket(key).setnx(key, value, duration, track)
210-
}
211-
212208
func (c *Cache[T]) bucket(key string) *bucket[T] {
213209
h := fnv.New32a()
214210
h.Write([]byte(key))

0 commit comments

Comments
 (0)