@@ -365,6 +365,15 @@ func (hyperCache *HyperCache[T]) startBackgroundJobs(ctx context.Context) {
365365 jobsCtx , cancel := context .WithCancel (ctx )
366366
367367 hyperCache .bgCancel = cancel
368+ // Ensure shutdown signaling always drives context cancellation, even when
369+ // stop consumers race to read the stop channel.
370+ go func (stop <- chan bool , done <- chan struct {}, cancel context.CancelFunc ) {
371+ select {
372+ case <- stop :
373+ cancel ()
374+ case <- done :
375+ }
376+ }(hyperCache .stop , jobsCtx .Done (), cancel )
368377
369378 hyperCache .startExpirationRoutine (jobsCtx )
370379 hyperCache .startEvictionRoutine (jobsCtx )
@@ -415,6 +424,13 @@ func (hyperCache *HyperCache[T]) handleExpirationSelect(ctx context.Context, tic
415424 case <- hyperCache .evictCh :
416425 // manual eviction trigger
417426 hyperCache .evictionLoop (ctx )
427+ case <- ctx .Done ():
428+ if tick != nil {
429+ tick .Stop ()
430+ }
431+
432+ return true
433+
418434 case <- hyperCache .stop :
419435 if tick != nil {
420436 tick .Stop ()
@@ -439,6 +455,11 @@ func (hyperCache *HyperCache[T]) startEvictionRoutine(ctx context.Context) {
439455 select {
440456 case <- tick .C :
441457 hyperCache .evictionLoop (ctx )
458+ case <- ctx .Done ():
459+ tick .Stop ()
460+
461+ return
462+
442463 case <- hyperCache .stop :
443464 tick .Stop ()
444465
@@ -967,17 +988,16 @@ const (
967988
968989// Stop function stops the expiration and eviction loops and closes the stop channel.
969990func (hyperCache * HyperCache [T ]) Stop (ctx context.Context ) error {
970- // Stop the expiration and eviction loops
971- wg := sync.WaitGroup {}
972-
973- wg .Go (func () {
974- hyperCache .stop <- true
975- })
976-
977- wg .Wait ()
991+ // Best-effort stop signal for listeners that still rely on stop channel.
992+ select {
993+ case hyperCache .stop <- true :
994+ default :
995+ }
978996
979997 if hyperCache .bgCancel != nil {
980998 hyperCache .bgCancel ()
999+
1000+ hyperCache .bgCancel = nil
9811001 }
9821002
9831003 hyperCache .once = sync.Once {}
@@ -992,8 +1012,6 @@ func (hyperCache *HyperCache[T]) Stop(ctx context.Context) error {
9921012 // Handle error
9931013 return err
9941014 }
995-
996- cancel ()
9971015 }
9981016
9991017 return nil
0 commit comments