Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Delete expired items before setting #132

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,14 +57,27 @@ func (c *cache) Set(k string, x interface{}, d time.Duration) {
if d > 0 {
e = time.Now().Add(d).UnixNano()
}

var item Item
var evicted bool

c.mu.Lock()
if c.onEvicted != nil {
item, evicted = c.items[k]
}

c.items[k] = Item{
Object: x,
Expiration: e,
}
// TODO: Calls to mu.Unlock are currently not deferred because defer
// adds ~200 ns (as of go1.)
c.mu.Unlock()

// try to call onEvicted if key existed before but the item is different
if evicted && item.Object != x {
c.onEvicted(k, item.Object)
}
}

func (c *cache) set(k string, x interface{}, d time.Duration) {
Expand Down
31 changes: 31 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1247,6 +1247,37 @@ func TestOnEvicted(t *testing.T) {
}
}

func TestOnEvictedCalledBeforeSet(t *testing.T) {
tc := New(DefaultExpiration, 0)
expiry := 1 * time.Nanosecond

works := false
tc.OnEvicted(func(k string, v interface{}) {
if k == "foo" && v.(int) == 3 {

works = true
}
tc.Set("bar", 4, DefaultExpiration)
})

tc.Set("foo", 3, expiry)
if tc.onEvicted == nil {
t.Fatal("tc.onEvicted is nil")
}

// calling Set again with the same key should evict
// the item if different
tc.Set("foo", 5, DefaultExpiration)

x, _ := tc.Get("bar")
if !works {
t.Fatal("works bool not true")
}
if x.(int) != 4 {
t.Error("bar was not 4")
}
}

func TestCacheSerialization(t *testing.T) {
tc := New(DefaultExpiration, 0)
testFillAndSerialize(t, tc)
Expand Down