Skip to content

Commit 62c3733

Browse files
Snawootswithek
authored andcommitted
fix double insertion into expiration queue
Signed-off-by: Vladislav Yarmak <[email protected]>
1 parent 9ca4fc0 commit 62c3733

File tree

2 files changed

+7
-7
lines changed

2 files changed

+7
-7
lines changed

cache.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ func (c *Cache[K, V]) set(key K, value V, ttl time.Duration) *Item[K, V] {
133133
ttl = c.options.ttl
134134
}
135135

136-
elem := c.get(key, false)
136+
elem := c.get(key, false, true)
137137
if elem != nil {
138138
// update/overwrite an existing item
139139
item := elem.Value.(*Item[K, V])
@@ -176,14 +176,14 @@ func (c *Cache[K, V]) set(key K, value V, ttl time.Duration) *Item[K, V] {
176176
// It returns nil if the item is not found or is expired.
177177
// Not safe for concurrent use by multiple goroutines without additional
178178
// locking.
179-
func (c *Cache[K, V]) get(key K, touch bool) *list.Element {
179+
func (c *Cache[K, V]) get(key K, touch bool, includeExpired bool) *list.Element {
180180
elem := c.items.values[key]
181181
if elem == nil {
182182
return nil
183183
}
184184

185185
item := elem.Value.(*Item[K, V])
186-
if item.isExpiredUnsafe() {
186+
if !includeExpired && item.isExpiredUnsafe() {
187187
return nil
188188
}
189189

@@ -218,7 +218,7 @@ func (c *Cache[K, V]) getWithOpts(key K, lockAndLoad bool, opts ...Option[K, V])
218218
c.items.mu.Lock()
219219
}
220220

221-
elem := c.get(key, !getOpts.disableTouchOnHit)
221+
elem := c.get(key, !getOpts.disableTouchOnHit, false)
222222

223223
if lockAndLoad {
224224
c.items.mu.Unlock()
@@ -436,7 +436,7 @@ func (c *Cache[K, V]) DeleteExpired() {
436436
// If the item is not found, the method is no-op.
437437
func (c *Cache[K, V]) Touch(key K) {
438438
c.items.mu.Lock()
439-
c.get(key, true)
439+
c.get(key, true, false)
440440
c.items.mu.Unlock()
441441
}
442442

@@ -469,7 +469,7 @@ func (c *Cache[K, V]) Items() map[K]*Item[K, V] {
469469

470470
items := make(map[K]*Item[K, V], len(c.items.values))
471471
for k := range c.items.values {
472-
item := c.get(k, false)
472+
item := c.get(k, false, false)
473473
if item != nil {
474474
items[k] = item.Value.(*Item[K, V])
475475
}

cache_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -404,7 +404,7 @@ func Test_Cache_get(t *testing.T) {
404404
oldItem.ttl = 0
405405
}
406406

407-
elem := cache.get(c.Key, c.Touch)
407+
elem := cache.get(c.Key, c.Touch, false)
408408

409409
if c.Key == notFoundKey {
410410
assert.Nil(t, elem)

0 commit comments

Comments
 (0)