@@ -91,14 +91,12 @@ type Cache[K comparable, V any] struct {
9191type Option [K comparable , V any ] func (* options [K , V ])
9292
9393type options [K comparable , V any ] struct {
94- ctx context.Context
9594 cache Interface [K , * Item [K , V ]]
9695 janitorInterval time.Duration
9796}
9897
9998func newOptions [K comparable , V any ]() * options [K , V ] {
10099 return & options [K , V ]{
101- ctx : context .Background (),
102100 cache : simple .NewCache [K , * Item [K , V ]](),
103101 janitorInterval : time .Minute ,
104102 }
@@ -149,25 +147,23 @@ func WithJanitorInterval[K comparable, V any](d time.Duration) Option[K, V] {
149147}
150148
151149// New creates a new thread safe Cache.
150+ // This function will be stopped an internal janitor when the cache is
151+ // no longer referenced anywhere.
152152//
153153// There are several Cache replacement policies available with you specified any options.
154154func New [K comparable , V any ](opts ... Option [K , V ]) * Cache [K , V ] {
155155 o := newOptions [K , V ]()
156156 for _ , optFunc := range opts {
157157 optFunc (o )
158158 }
159+ ctx , cancel := context .WithCancel (context .Background ())
159160 cache := & Cache [K , V ]{
160- cache : o .cache ,
161- }
162- if o .ctx == context .Background () {
163- ctx , cancel := context .WithCancel (o .ctx )
164- cache .janitor = newJanitor (ctx , o .janitorInterval )
165- runtime .SetFinalizer (cache , func (self * Cache [K , V ]) {
166- cancel ()
167- })
168- } else {
169- cache .janitor = newJanitor (o .ctx , o .janitorInterval )
161+ cache : o .cache ,
162+ janitor : newJanitor (ctx , o .janitorInterval ),
170163 }
164+ runtime .SetFinalizer (cache , func (self * Cache [K , V ]) {
165+ cancel ()
166+ })
171167 return cache
172168}
173169
@@ -181,7 +177,7 @@ func NewContext[K comparable, V any](ctx context.Context, opts ...Option[K, V])
181177 }
182178 return & Cache [K , V ]{
183179 cache : o .cache ,
184- janitor : newJanitor (o . ctx , o .janitorInterval ),
180+ janitor : newJanitor (ctx , o .janitorInterval ),
185181 }
186182}
187183
0 commit comments