cache icon indicating copy to clipboard operation
cache copied to clipboard

should pass pointer for cache.Cache to prevent original object be GCed

Open xiaoyexu opened this issue 2 years ago • 0 comments

When the cache is created, a finalizer will stop ticking if no reference to the pointer

func New(defaultExpiration, cleanupInterval time.Duration) *Cache { c := newCache(defaultExpiration) // This trick ensures that the janitor goroutine (which--granted it // was enabled--is running DeleteExpired on c forever) does not keep // the returned C object from being garbage collected. When it is // garbage collected, the finalizer stops the janitor goroutine, after // which c can be collected. C := &Cache{c} if cleanupInterval > 0 { runJanitor(c, cleanupInterval) runtime.SetFinalizer(C, stopJanitor) } return C }

if InMemoryStore is using value assignment, the point may change which will cause finalizer be triggered and stopped ticking &InMemoryStore{cache.New(defaultExpiration, time.Minute)}

Therefore should use pointer here.

xiaoyexu avatar Jul 23 '21 08:07 xiaoyexu