Skip to content

Commit

Permalink
This is an automated cherry-pick of tikv#9048
Browse files Browse the repository at this point in the history
close tikv#9047

Signed-off-by: ti-chi-bot <ti-community-prow-bot@tidb.io>
  • Loading branch information
bufferflies authored and ti-chi-bot committed Feb 10, 2025
1 parent bf361c8 commit a4ba7b8
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 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"

"github.com/pingcap/log"
Expand All @@ -37,18 +38,26 @@ type ttlCache struct {
items map[interface{}]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{
<<<<<<< HEAD

Check failure on line 48 in pkg/cache/ttl.go

View workflow job for this annotation

GitHub Actions / statics

syntax error: unexpected <<, expecting expression
ctx: ctx,
items: make(map[interface{}]ttlCacheItem),

Check failure on line 50 in pkg/cache/ttl.go

View workflow job for this annotation

GitHub Actions / statics

syntax error: unexpected ] at end of statement
ttl: duration,
gcInterval: gcInterval,
=======
ctx: ctx,
items: make(map[any]ttlCacheItem),
ttl: duration,
gcInterval: gcInterval,
isGCRunning: atomic.Bool{},

Check failure on line 58 in pkg/cache/ttl.go

View workflow job for this annotation

GitHub Actions / statics

syntax error: unexpected comma after top level declaration
>>>>>>> c92da8364 (cache: lazy gc in ttl (#9048))

Check failure on line 59 in pkg/cache/ttl.go

View workflow job for this annotation

GitHub Actions / statics

invalid character U+0023 '#'
}

go c.doGC()
return c
}

Expand All @@ -61,7 +70,9 @@ func (c *ttlCache) put(key interface{}, value interface{}) {
func (c *ttlCache) putWithTTL(key interface{}, value interface{}, 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 @@ -161,6 +172,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 a4ba7b8

Please sign in to comment.