Skip to content

Commit a47156d

Browse files
author
chenyijun.266846
committed
feat: add existing for setnx2
1 parent c0806d2 commit a47156d

File tree

2 files changed

+15
-6
lines changed

2 files changed

+15
-6
lines changed

bucket.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -59,12 +59,12 @@ func (b *bucket[T]) setnx(key string, value T, duration time.Duration, track boo
5959
return newItem
6060
}
6161

62-
func (b *bucket[T]) setnx2(key string, f func() T, duration time.Duration, track bool) *Item[T] {
62+
func (b *bucket[T]) setnx2(key string, f func() T, duration time.Duration, track bool) (*Item[T], bool) {
6363
b.RLock()
6464
item := b.lookup[key]
6565
b.RUnlock()
6666
if item != nil {
67-
return item
67+
return item, true
6868
}
6969

7070
b.Lock()
@@ -73,14 +73,14 @@ func (b *bucket[T]) setnx2(key string, f func() T, duration time.Duration, track
7373
// check again under write lock
7474
item = b.lookup[key]
7575
if item != nil {
76-
return item
76+
return item, true
7777
}
7878

7979
expires := time.Now().Add(duration).UnixNano()
8080
newItem := newItem(key, f(), expires, track)
8181

8282
b.lookup[key] = newItem
83-
return newItem
83+
return newItem, false
8484
}
8585

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

cache.go

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -126,8 +126,17 @@ func (c *Cache[T]) Setnx(key string, value T, duration time.Duration) {
126126

127127
// Setnx2 set the value in the cache for the specified duration if not exists
128128
func (c *Cache[T]) Setnx2(key string, f func() T, duration time.Duration) *Item[T] {
129-
item := c.bucket(key).setnx2(key, f, duration, false)
130-
c.promotables <- item
129+
item, existing := c.bucket(key).setnx2(key, f, duration, false)
130+
// consistent with Get
131+
if existing && !item.Expired() {
132+
select {
133+
case c.promotables <- item:
134+
default:
135+
}
136+
// consistent with set
137+
} else if !existing {
138+
c.promotables <- item
139+
}
131140
return item
132141
}
133142

0 commit comments

Comments
 (0)