Skip to content

Commit

Permalink
cache: lazy gc in ttl (#9048)
Browse files Browse the repository at this point in the history
close #9047

Signed-off-by: 童剑 <1045931706@qq.com>
  • Loading branch information
bufferflies authored Feb 10, 2025
1 parent 3af31b2 commit c92da83
Showing 1 changed file with 16 additions and 7 deletions.
23 changes: 16 additions & 7 deletions pkg/cache/ttl.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package cache

import (
"context"
"sync/atomic"
"time"

"go.uber.org/zap"
Expand All @@ -39,18 +40,19 @@ type ttlCache struct {
items map[any]ttlCacheItem
ttl time.Duration
gcInterval time.Duration
// isGCRunning is used to avoid running GC multiple times.
isGCRunning atomic.Bool
}

// NewTTL returns a new TTL cache.
func newTTL(ctx context.Context, gcInterval time.Duration, duration time.Duration) *ttlCache {
c := &ttlCache{
ctx: ctx,
items: make(map[any]ttlCacheItem),
ttl: duration,
gcInterval: gcInterval,
ctx: ctx,
items: make(map[any]ttlCacheItem),
ttl: duration,
gcInterval: gcInterval,
isGCRunning: atomic.Bool{},
}

go c.doGC()
return c
}

Expand All @@ -63,7 +65,9 @@ func (c *ttlCache) put(key any, value any) {
func (c *ttlCache) putWithTTL(key any, value any, ttl time.Duration) {
c.Lock()
defer c.Unlock()

if len(c.items) == 0 && c.isGCRunning.CompareAndSwap(false, true) {
go c.doGC()
}
c.items[key] = ttlCacheItem{
value: value,
expire: time.Now().Add(ttl),
Expand Down Expand Up @@ -163,6 +167,11 @@ func (c *ttlCache) doGC() {
}
}
}
if len(c.items) == 0 && c.isGCRunning.CompareAndSwap(true, false) {
c.Unlock()
log.Debug("TTL GC items is empty exit")
return
}
c.Unlock()
log.Debug("TTL GC items", zap.Int("count", count))
case <-c.ctx.Done():
Expand Down

0 comments on commit c92da83

Please sign in to comment.