Skip to content

Commit c9e136c

Browse files
committedFeb 12, 2021
Prevent background loop from locking the record if not needed
1 parent 6cfd9bd commit c9e136c

File tree

2 files changed

+13
-18
lines changed

2 files changed

+13
-18
lines changed
 

‎cache.go

+4-10
Original file line numberDiff line numberDiff line change
@@ -392,11 +392,6 @@ func (c *Cache) processRecords(now int64) {
392392
if !r.IsActive() {
393393
return true
394394
}
395-
r.mu.RLock()
396-
defer r.mu.RUnlock()
397-
if !r.IsActive() {
398-
return true
399-
}
400395
if r.expired(now) {
401396
c.mu.Lock()
402397
defer c.mu.Unlock()
@@ -405,11 +400,10 @@ func (c *Cache) processRecords(now int64) {
405400
}
406401
return true
407402
}
408-
if !c.lfuEnabled {
409-
return true
410-
}
411-
if hits := atomic.SwapUint32(&r.hits, 0); hits > 0 {
412-
c.list.MoveForward(r.ring, hits)
403+
if c.lfuEnabled {
404+
if hits := atomic.SwapUint32(&r.hits, 0); hits > 0 {
405+
c.list.MoveForward(r.ring, hits)
406+
}
413407
}
414408
return true
415409
})

‎record.go

+9-8
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,13 @@ const (
1313
)
1414

1515
type record struct {
16-
mu sync.RWMutex
17-
wg sync.WaitGroup
18-
ring *ring.Ring
16+
mu sync.RWMutex
17+
wg sync.WaitGroup
18+
readers uint32
19+
ring *ring.Ring
1920

2021
value interface{}
2122
expires int64
22-
readers uint32
2323
hits uint32
2424
state uint32
2525
}
@@ -67,8 +67,8 @@ func (r *record) LoadAndReset() (interface{}, bool) {
6767
}
6868
value := r.value
6969
r.value = nil
70-
r.expires = 0
71-
r.hits = 0
70+
atomic.StoreInt64(&r.expires, 0)
71+
atomic.StoreUint32(&r.hits, 0)
7272
return value, true
7373
}
7474

@@ -78,10 +78,11 @@ func (r *record) init(value interface{}, ttl time.Duration) {
7878
}
7979
r.value = value
8080
if ttl > 0 {
81-
r.expires = time.Now().Add(ttl).UnixNano()
81+
atomic.StoreInt64(&r.expires, time.Now().Add(ttl).UnixNano())
8282
}
8383
}
8484

8585
func (r *record) expired(now int64) bool {
86-
return r.expires > 0 && r.expires < now
86+
expires := atomic.LoadInt64(&r.expires)
87+
return expires > 0 && expires < now
8788
}

0 commit comments

Comments
 (0)