fix(cache,mem): replace finalizers with runtime.AddCleanup (#2535)

This commit is contained in:
j2rong4cn
2026-06-01 01:50:20 +08:00
committed by GitHub
parent ac80fe19bf
commit 9282e8ef09
2 changed files with 15 additions and 10 deletions
+5 -6
View File
@@ -18,6 +18,7 @@ type HybridCache struct {
memoryOffset uint64
backingStore BackingStore
backingOffset uint64
cleanup runtime.Cleanup
}
// HybridCache本身是一个大的Block,支持分块成多个小的Block
@@ -99,11 +100,15 @@ func (hc *HybridCache) initFileCache() error {
if err != nil {
return err
}
hc.cleanup = runtime.AddCleanup(hc, func(file BackingStore) {
_ = file.Close()
}, file)
hc.backingStore = file
return nil
}
func (hc *HybridCache) Close() error {
hc.cleanup.Stop()
var err error
if hc.memoryStore != nil {
err = hc.memoryStore.Free()
@@ -228,12 +233,6 @@ func NewHybridCache(blockSize, maxMemorySize uint64) (hc *HybridCache, err error
return nil, errors.Join(err, err2)
}
}
runtime.SetFinalizer(hc, func(hc *HybridCache) {
if hc.backingStore != nil {
_ = hc.backingStore.Close()
hc.backingStore = nil
}
})
return hc, nil
}
+10 -4
View File
@@ -58,15 +58,16 @@ func NewGuardedMemory(cap, max uint64) (m LinearMemory, err error) {
if s, ok := m.(interface{ SetGrowCheck(GrowCheck) }); ok {
s.SetGrowCheck(MemoryGrowCheck)
}
gm := &guardedMemory{m}
runtime.SetFinalizer(gm, func(gm *guardedMemory) {
gm.Free()
})
gm := &guardedMemory{LinearMemory: m}
gm.cleanup = runtime.AddCleanup(gm, func(m LinearMemory) {
m.Free()
}, m)
return gm, nil
}
type guardedMemory struct {
LinearMemory
cleanup runtime.Cleanup
}
func (s *guardedMemory) Reallocate(size uint64) (all []byte, err error) {
@@ -77,3 +78,8 @@ func (s *guardedMemory) Reallocate(size uint64) (all []byte, err error) {
}()
return s.LinearMemory.Reallocate(size)
}
func (s *guardedMemory) Free() error {
s.cleanup.Stop()
return s.LinearMemory.Free()
}