Skip to content

Commit

Permalink
Merge pull request #91 from nirrattner/expose-context
Browse files Browse the repository at this point in the history
Expose context for auto evict lifecycle
  • Loading branch information
jamiealquiza authored Jul 3, 2023
2 parents 309030b + 0d0d864 commit 9497edd
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
6 changes: 5 additions & 1 deletion bicache.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ type Config struct {
EvictLog bool
ShardCount int
NoOverflow bool
Context context.Context
}

// Entry is a container type for scored
Expand Down Expand Up @@ -141,7 +142,10 @@ func New(c *Config) (*Bicache, error) {
}
}

ctx, cf := context.WithCancel(context.Background())
if c.Context == nil {
c.Context = context.Background()
}
ctx, cf := context.WithCancel(c.Context)

cache := &Bicache{
shards: shards,
Expand Down
42 changes: 42 additions & 0 deletions bicache_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package bicache_test

import (
"context"
"fmt"
"log"
"strconv"
"testing"
Expand Down Expand Up @@ -222,3 +224,43 @@ func TestPromoteEvict(t *testing.T) {
}
}
}

func TestCanceledContext(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
c, _ := bicache.New(&bicache.Config{
MRUSize: 30,
ShardCount: 2,
AutoEvict: 1000,
Context: ctx,
})

for i := 0; i < 40; i++ {
c.Set(fmt.Sprintf("initial-%d", i), "value")
}

log.Printf("Sleeping for 2 seconds to allow evictions")
time.Sleep(2 * time.Second)

stats := c.Stats()

// Check that auto evict is maintaining capacity
if stats.MRUSize != 30 {
t.Error("Unexpected initial MRU count")
}

// Cancel context to close auto evict
cancel()

for i := 0; i < 40; i++ {
c.Set(fmt.Sprintf("after-cancel-%d", i), "value")
}
log.Printf("Sleeping for 2 seconds to allow evictions")
time.Sleep(2 * time.Second)

stats = c.Stats()

// Check that auto evict is not active and not maintaining capacity
if stats.MRUSize != 70 {
t.Error("Unexpected MRU count after cancel")
}
}

0 comments on commit 9497edd

Please sign in to comment.