Skip to content

Commit

Permalink
Fix ring not being removed correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
mgnsk committed Feb 9, 2021
1 parent e2a8180 commit 54f3427
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 5 deletions.
2 changes: 1 addition & 1 deletion cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,8 +184,8 @@ func (c *Cache) Evict(key interface{}) {
}
c.wg.Add(1)
go func() {
r := value.(*record)
defer c.wg.Done()
r := value.(*record)
value, ok := r.LoadAndDelete()
if !ok {
return
Expand Down
2 changes: 1 addition & 1 deletion cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ var _ = Describe("overflow when setting values", func() {
return nil, nil
})
closer.Close()
Expect(c.Len()).To(BeNumerically("<=", n+overflow))
Expect(c.Len()).To(BeNumerically("<=", n), "capacity cannot be exceeded")
}

Eventually(func() uint64 {
Expand Down
19 changes: 16 additions & 3 deletions ring.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,11 @@ func (l *lfuRing) Push(key interface{}, r *ring.Ring) (lfuKey interface{}) {
l.cursor = r
l.size++
if l.capacity > 0 && l.size > l.capacity {
return l.unlink(l.cursor.Next())
lfuKey = l.unlink(l.cursor.Next())
if lfuKey == key {
panic("evcache: lfuKey cannot be key")
}
return lfuKey
}
return nil
}
Expand All @@ -48,8 +52,9 @@ func (l *lfuRing) Push(key interface{}, r *ring.Ring) (lfuKey interface{}) {
func (l *lfuRing) Remove(r *ring.Ring) (key interface{}) {
l.mu.Lock()
defer l.mu.Unlock()
if r == r.Next() && r != l.cursor {
// A single ring element not belonging to lfuRing.
if r.Value == nil {
// An overflowed ring which was already unlinked by l.Push
// but the record not yet evicted.
return nil
}
return l.unlink(r)
Expand All @@ -59,6 +64,11 @@ func (l *lfuRing) Remove(r *ring.Ring) (key interface{}) {
func (l *lfuRing) Promote(r *ring.Ring, hits uint32) {
l.mu.Lock()
defer l.mu.Unlock()
if r.Value == nil {
// An overflowed ring which was already unlinked by l.Push
// but the record not yet evicted.
return
}
if l.cursor == nil {
panic("evcache: cursor must not be nil")
}
Expand All @@ -83,6 +93,9 @@ func (l *lfuRing) Promote(r *ring.Ring, hits uint32) {
}

func (l *lfuRing) unlink(r *ring.Ring) (key interface{}) {
if r.Value == nil {
panic("evcache: r.Value must not be nil")
}
if l.cursor == nil {
panic("evcache: cursor must not be nil")
}
Expand Down

0 comments on commit 54f3427

Please sign in to comment.