patrickmn / go-cache

An in-memory key:value store/cache (similar to Memcached) library for Go, suitable for single-machine applications.
https://patrickmn.com/projects/go-cache/
MIT License
8.16k stars 874 forks source link

why struct Cache contains pointer to cache? #142

Open chengxwcq opened 3 years ago

chengxwcq commented 3 years ago

it looks like struct cache is unnecessary in the code. I notice the comment // If this is confusing, see the comment at the bottom of New(), but i didn't find any explaination

thediveo commented 2 years ago

https://github.com/patrickmn/go-cache/blob/46f407853014144407b6c2ec7ccc76bf67958d93/cache.go#L1115

john-nash-rs commented 1 year ago

IMO, Since, the janitor is working in a go routine on cache , c object. It will never be available for garbage collection. Hence, Cache struct is designed to have cache as a field. If Cache struct is garbage collected, stopJanitor is called using the runtime.setFinalizer. runtime.setFinalizer is used to call a function, here stopJanitor, when the first operand , here C, is garbage collected.