From c851e6582d06cc74a297c00f13f8c8a9ca45cdfc Mon Sep 17 00:00:00 2001 From: Yusuke Kato Date: Tue, 17 Sep 2024 16:58:26 +0900 Subject: [PATCH] [BUGFIX] Fixes to expChan reachability during mass data deletion (#140) Signed-off-by: kpango --- example/main.go | 14 +++++++++++++- gache.go | 10 ++++++---- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/example/main.go b/example/main.go index d2350d0..be8c219 100644 --- a/example/main.go +++ b/example/main.go @@ -146,10 +146,22 @@ func main() { return true }) + runtime.GC() + gch := gache.New[int64]().EnableExpiredHook(). + SetExpiredHook(func(ctx context.Context, key string) { + glg.Debugf("key=%v expired", key) + }). + StartExpired(context.Background(), time.Second*10) + for i := 0; i < 10000; i++ { + gch.SetWithExpire("sample-"+strconv.Itoa(i), int64(i), time.Second*5) + } + time.Sleep(time.Second * 20) + glg.Debugf("length: %d", gch.Len()) + runtime.GC() gcs := gache.New[string]() maxCnt := 10000000 - digitLen := len(strconv.Itoa(maxCnt)) + digitLen := len(strconv.Itoa(maxCnt)) for i := 0; i < maxCnt; i++ { if i%1000 == 0 { // runtime.ReadMemStats(&m) diff --git a/gache.go b/gache.go index e11da65..78e9e0f 100755 --- a/gache.go +++ b/gache.go @@ -144,20 +144,22 @@ func (g *gache[V]) SetExpiredHook(f func(context.Context, string)) Gache[V] { // StartExpired starts delete expired value daemon func (g *gache[V]) StartExpired(ctx context.Context, dur time.Duration) Gache[V] { go func() { - tick := time.NewTicker(dur) var cancel context.CancelFunc ctx, cancel = context.WithCancel(ctx) g.cancel.Store(&cancel) + tick := time.NewTicker(dur) for { select { case <-ctx.Done(): tick.Stop() return - case <-tick.C: - g.DeleteExpired(ctx) - runtime.Gosched() case key := <-g.expChan: go g.expFunc(ctx, key) + case <-tick.C: + go func() { + g.DeleteExpired(ctx) + runtime.Gosched() + }() } } }()