Skip to content

Commit

Permalink
Drop unused field, simplify expiry
Browse files Browse the repository at this point in the history
  • Loading branch information
mgnsk committed Jan 25, 2021
1 parent dbb0538 commit 86f0c10
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 34 deletions.
67 changes: 35 additions & 32 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -256,22 +256,6 @@ func (c *Cache) Close() error {
return nil
}

func (c *Cache) runAfterEvict(key interface{}, r *record) {
if r.elem != nil {
c.listMu.Lock()
c.list.Remove(r.elem)
c.listMu.Unlock()
}
if c.afterEvict != nil {
c.wg.Add(1)
go func() {
defer c.wg.Done()
r.wg.Wait()
c.afterEvict(key, r.value)
}()
}
}

func (c *Cache) swap(key interface{}, old, new *record) (swapped bool) {
old.mu.Lock()
defer old.mu.Unlock()
Expand All @@ -287,7 +271,6 @@ func (c *Cache) swap(key interface{}, old, new *record) (swapped bool) {
func (c *Cache) initRecord(r *record, value interface{}, ttl time.Duration) {
r.value = value
if ttl > 0 {
r.ttl = ttl
r.expires = time.Now().Add(ttl).UnixNano()
c.onceLoop.Do(func() {
go c.runEvictionLoop()
Expand Down Expand Up @@ -381,21 +364,7 @@ func (c *Cache) processRecords(now int64) {
return true
}
if r.expires > 0 && r.expires < now {
rec, loaded := c.records.LoadAndDelete(key)
if !loaded {
return true
}
if r != rec.(*record) {
panic("evcache: invariant failed: record is not the same")
}
r.delete()
go func() {
// Lock to guard record's waitgroup.
r.mu.Lock()
defer r.mu.Unlock()
c.runAfterEvict(key, r)
atomic.AddUint32(&c.size, ^uint32(0))
}()
c.expireRecord(key, r)
return true
}
if c.capacity == 0 {
Expand Down Expand Up @@ -429,6 +398,40 @@ func (c *Cache) processRecords(now int64) {
})
}

func (c *Cache) expireRecord(key interface{}, r *record) {
rec, loaded := c.records.LoadAndDelete(key)
if !loaded {
return
}
if r != rec.(*record) {
panic("evcache: invariant failed: record is not the same")
}
r.delete()
go func() {
// Lock to guard record's waitgroup.
r.mu.Lock()
defer r.mu.Unlock()
c.runAfterEvict(key, r)
atomic.AddUint32(&c.size, ^uint32(0))
}()
}

func (c *Cache) runAfterEvict(key interface{}, r *record) {
if r.elem != nil {
c.listMu.Lock()
c.list.Remove(r.elem)
c.listMu.Unlock()
}
if c.afterEvict != nil {
c.wg.Add(1)
go func() {
defer c.wg.Done()
r.wg.Wait()
c.afterEvict(key, r.value)
}()
}
}

func (c *Cache) evictLFU() {
pop := func() (key interface{}, success bool) {
c.listMu.Lock()
Expand Down
2 changes: 0 additions & 2 deletions record.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"container/list"
"sync"
"sync/atomic"
"time"
)

type record struct {
Expand All @@ -14,7 +13,6 @@ type record struct {
wg sync.WaitGroup
deleted uint32
hits uint32
ttl time.Duration
expires int64
}

Expand Down

0 comments on commit 86f0c10

Please sign in to comment.