Skip to content

Commit 61a0a25

Browse files
committed
make context a first class citizen
1 parent b548945 commit 61a0a25

2 files changed

Lines changed: 4 additions & 21 deletions

File tree

mempot.go

Lines changed: 3 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,9 @@ import (
99

1010
// Config allows to alter the configuration of a Cache.
1111
//
12-
// Context is by default an empty background context.
1312
// DefaultTTL is by default 15 minutes.
1413
// CleanupInterval is by default 5 minutes.
1514
type Config struct {
16-
Context context.Context
1715
DefaultTTL time.Duration
1816
CleanupInterval time.Duration
1917
}
@@ -23,11 +21,9 @@ type Cache[K comparable, T any] struct {
2321
mut sync.RWMutex
2422
data map[K]Item[T]
2523

24+
ctx context.Context
2625
defaultTTL time.Duration
2726
cleanupInterval time.Duration
28-
29-
ctx context.Context
30-
cancel context.CancelFunc
3127
}
3228

3329
// Item is a unit of typed data which can be cached and has an expiration as Unix epoch.
@@ -42,19 +38,14 @@ func (i *Item[T]) Expired() bool {
4238
}
4339

4440
// NewCache create a new Cache instance with K as key and T as data.
45-
func NewCache[K comparable, T any](cfg Config) *Cache[K, T] {
41+
func NewCache[K comparable, T any](ctx context.Context, cfg Config) *Cache[K, T] {
4642
c := &Cache[K, T]{
4743
data: make(map[K]Item[T]),
44+
ctx: ctx,
4845
defaultTTL: time.Minute * 15,
4946
cleanupInterval: time.Minute * 5,
5047
}
5148

52-
c.ctx, c.cancel = context.WithCancel(context.Background())
53-
54-
if cfg.Context != nil {
55-
c.ctx = cfg.Context
56-
}
57-
5849
if cfg.DefaultTTL > 0 {
5950
c.defaultTTL = cfg.DefaultTTL
6051
}
@@ -135,12 +126,6 @@ func (c *Cache[K, T]) Reset() {
135126
c.mut.Unlock()
136127
}
137128

138-
// Cancel will cancel the default Context of the Cache which stops the cleanup ticker.
139-
// This only has an effect when the Cache has not been created with a custom context.
140-
func (c *Cache[K, T]) Cancel() {
141-
c.cancel()
142-
}
143-
144129
func (c *Cache[K, T]) cleanup() {
145130
ticker := time.NewTicker(c.cleanupInterval)
146131

mempot_test.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,7 @@ const data = "bar"
1313
func TestCache(t *testing.T) {
1414
ctx, cancel := context.WithCancel(context.Background())
1515

16-
cache := NewCache[string, string](Config{
17-
Context: ctx,
16+
cache := NewCache[string, string](ctx, Config{
1817
DefaultTTL: 30 * time.Second,
1918
CleanupInterval: 4 * time.Second,
2019
})
@@ -69,7 +68,6 @@ func TestCache(t *testing.T) {
6968
}
7069

7170
cancel()
72-
cache.Cancel()
7371

7472
time.Sleep(1 * time.Second)
7573
}

0 commit comments

Comments
 (0)