diff --git a/client/cache/random_expired_cache.go b/client/cache/random_expired_cache.go index 59b3d2ad..afa2e9b9 100644 --- a/client/cache/random_expired_cache.go +++ b/client/cache/random_expired_cache.go @@ -17,6 +17,7 @@ package cache import ( "context" "math/rand" + "sync/atomic" "time" ) @@ -44,12 +45,25 @@ func NewRandomExpireCache(adapter Cache, opts ...RandomExpireCacheOption) Cache fn(&rec) } if rec.Offset == nil { - rec.Offset = defaultExpiredFunc + rec.Offset = defaultExpiredFunc() } return &rec } -// defaultExpiredFunc genreate random time offset expired -func defaultExpiredFunc() time.Duration { - return time.Duration(rand.Intn(5)+3) * time.Second +// defaultExpiredFunc return a func that used to generate random time offset (range: [3s,8s)) expired +func defaultExpiredFunc() func() time.Duration { + const size = 5 + var randTimes [size]time.Duration + for i := range randTimes { + randTimes[i] = time.Duration(i + 3) + } + // shuffle values + for i := range randTimes { + n := rand.Intn(size) + randTimes[i], randTimes[n] = randTimes[n], randTimes[i] + } + var i uint64 + return func() time.Duration { + return randTimes[atomic.AddUint64(&i, 1)%size] + } } diff --git a/client/cache/random_expired_cache_test.go b/client/cache/random_expired_cache_test.go index b1af5840..924db5f3 100644 --- a/client/cache/random_expired_cache_test.go +++ b/client/cache/random_expired_cache_test.go @@ -29,7 +29,7 @@ func TestRandomExpireCache(t *testing.T) { // cache := NewRandomExpireCache(bm) cache := NewRandomExpireCache(bm, func(opt *RandomExpireCache) { - opt.offset = defaultExpiredFunc + opt.Offset = defaultExpiredFunc() }) timeoutDuration := 3 * time.Second