@@ -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.
1514type 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-
144129func (c * Cache [K , T ]) cleanup () {
145130 ticker := time .NewTicker (c .cleanupInterval )
146131
0 commit comments