Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cache: lazy gc in ttl #9048

Merged
merged 2 commits into from
Feb 10, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()
bufferflies marked this conversation as resolved.
Show resolved Hide resolved
}
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