diff --git a/cache.go b/cache.go index 892e5ad..54578e3 100644 --- a/cache.go +++ b/cache.go @@ -127,7 +127,7 @@ retry: cl := &call[V]{} cl.wg.Add(1) c.calls[key] = cl - go c.set(context.Background(), cl, key) // Use empty context so as not to be cancelled by the original context + go c.set(context.WithoutCancel(ctx), cl, key) } c.stats.GraceHits++ c.mu.Unlock() @@ -187,7 +187,7 @@ func (c *cache[K, V]) GetIfExists(key K) (v V, ok bool) { } // Notify instructs the cache to retrieve value for key if value does not exist or is stale, in a non-blocking manner. -func (c *cache[K, V]) Notify(key K) { +func (c *cache[K, V]) Notify(ctx context.Context, key K) { // Record time as soon as Get is called *before acquiring the lock* - this maximizes the reuse of values calledAt := monoTimeNow() c.mu.Lock() @@ -205,7 +205,7 @@ func (c *cache[K, V]) Notify(key K) { cl := &call[V]{} cl.wg.Add(1) c.calls[key] = cl - go c.set(context.Background(), cl, key) // Use empty context so as not to be cancelled by the original context + go c.set(context.WithoutCancel(ctx), cl, key) } c.mu.Unlock() } diff --git a/cache_test.go b/cache_test.go index 0447682..9b42c90 100644 --- a/cache_test.go +++ b/cache_test.go @@ -456,7 +456,7 @@ func TestCache_Notify(t *testing.T) { t0 := time.Now() // Notify value retrieval - this should launch goroutine in background - cache.Notify("k1") + cache.Notify(context.Background(), "k1") // Test that value is still not here _, ok := cache.GetIfExists("k1") assert.False(t, ok) @@ -477,7 +477,7 @@ func TestCache_Notify(t *testing.T) { assert.EqualValues(t, 1, cnt) // t=750ms, notify once again - this should do *nothing* - cache.Notify("k1") + cache.Notify(context.Background(), "k1") time.Sleep(750 * time.Millisecond) // t=1500ms, assert that value was replaced only once