@@ -91,14 +91,12 @@ type Cache[K comparable, V any] struct {
91
91
type Option [K comparable , V any ] func (* options [K , V ])
92
92
93
93
type options [K comparable , V any ] struct {
94
- ctx context.Context
95
94
cache Interface [K , * Item [K , V ]]
96
95
janitorInterval time.Duration
97
96
}
98
97
99
98
func newOptions [K comparable , V any ]() * options [K , V ] {
100
99
return & options [K , V ]{
101
- ctx : context .Background (),
102
100
cache : simple .NewCache [K , * Item [K , V ]](),
103
101
janitorInterval : time .Minute ,
104
102
}
@@ -149,25 +147,23 @@ func WithJanitorInterval[K comparable, V any](d time.Duration) Option[K, V] {
149
147
}
150
148
151
149
// 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.
152
152
//
153
153
// There are several Cache replacement policies available with you specified any options.
154
154
func New [K comparable , V any ](opts ... Option [K , V ]) * Cache [K , V ] {
155
155
o := newOptions [K , V ]()
156
156
for _ , optFunc := range opts {
157
157
optFunc (o )
158
158
}
159
+ ctx , cancel := context .WithCancel (context .Background ())
159
160
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 ),
170
163
}
164
+ runtime .SetFinalizer (cache , func (self * Cache [K , V ]) {
165
+ cancel ()
166
+ })
171
167
return cache
172
168
}
173
169
@@ -181,7 +177,7 @@ func NewContext[K comparable, V any](ctx context.Context, opts ...Option[K, V])
181
177
}
182
178
return & Cache [K , V ]{
183
179
cache : o .cache ,
184
- janitor : newJanitor (o . ctx , o .janitorInterval ),
180
+ janitor : newJanitor (ctx , o .janitorInterval ),
185
181
}
186
182
}
187
183
0 commit comments