Skip to content

Commit c851e65

Browse files
authored
[BUGFIX] Fixes to expChan reachability during mass data deletion (#140)
Signed-off-by: kpango <[email protected]>
1 parent e54a136 commit c851e65

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

example/main.go

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,10 +146,22 @@ func main() {
146146
return true
147147
})
148148

149+
runtime.GC()
150+
gch := gache.New[int64]().EnableExpiredHook().
151+
SetExpiredHook(func(ctx context.Context, key string) {
152+
glg.Debugf("key=%v expired", key)
153+
}).
154+
StartExpired(context.Background(), time.Second*10)
155+
for i := 0; i < 10000; i++ {
156+
gch.SetWithExpire("sample-"+strconv.Itoa(i), int64(i), time.Second*5)
157+
}
158+
time.Sleep(time.Second * 20)
159+
glg.Debugf("length: %d", gch.Len())
160+
149161
runtime.GC()
150162
gcs := gache.New[string]()
151163
maxCnt := 10000000
152-
digitLen := len(strconv.Itoa(maxCnt))
164+
digitLen := len(strconv.Itoa(maxCnt))
153165
for i := 0; i < maxCnt; i++ {
154166
if i%1000 == 0 {
155167
// runtime.ReadMemStats(&m)

gache.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -144,20 +144,22 @@ func (g *gache[V]) SetExpiredHook(f func(context.Context, string)) Gache[V] {
144144
// StartExpired starts delete expired value daemon
145145
func (g *gache[V]) StartExpired(ctx context.Context, dur time.Duration) Gache[V] {
146146
go func() {
147-
tick := time.NewTicker(dur)
148147
var cancel context.CancelFunc
149148
ctx, cancel = context.WithCancel(ctx)
150149
g.cancel.Store(&cancel)
150+
tick := time.NewTicker(dur)
151151
for {
152152
select {
153153
case <-ctx.Done():
154154
tick.Stop()
155155
return
156-
case <-tick.C:
157-
g.DeleteExpired(ctx)
158-
runtime.Gosched()
159156
case key := <-g.expChan:
160157
go g.expFunc(ctx, key)
158+
case <-tick.C:
159+
go func() {
160+
g.DeleteExpired(ctx)
161+
runtime.Gosched()
162+
}()
161163
}
162164
}
163165
}()

0 commit comments

Comments
 (0)