samueleaton/cache-hash

Maybe add an autopurge?

Opened this issue · 6 comments

Hello! I've been using your module and think that I need the cache to delete its contents from time to time, because 'dead' objects start to accrue in a long running process.

A tiny looping fibre that just runs purge_stale+sleep is all I needed to add.. but it would be cool if you had it builtin to the module, possibly turned on/off with a flag.

Alternatively you could clean out old values every 'x' calls to set/get, similar to a memory garbage collector.

Thoughts?

how's this?

.set_purge_interval(interval : Time::Span, stale_only : Bool = true)

Sets an interval where key/value pairs will automatically be purged.

Example:

cache_hash = CacheHash(String).new(1.minute)
cache_hash.set_purge_interval(10.minutes) # stale_only defaults to true
cache_hash = CacheHash(String).new(1.minute)
cache_hash.set_purge_interval(10.minutes, stale_only: false) # deletes all values, not just stale ones

Ooo, that was fast! Yeah that seems cool.. Except maybe use a loop construct to do the looping, it would be a disaster if llvm didn't optimize the recursive call.

.. It might also be a good idea to make the collection setup as something you can pass in to new(), but that's just my preference and I guess it doesn't matter too much.

so you're saying something like this?

cache_hash = CacheHash(String).new(1.minute, purge_interval: 1.hour, purge_stale_only: true)

Sorry, just woke up.

That looks good -- I suggested it because autopurge is probably a highly desirable feature worth enabling at creation time. It also means I don't need to 'tweak' the object which feels less "side-effecty" (uhh highly technical functional programming term).

To be clear though, it's your library and you can design it however the heck you want. The current MR definitely works as-is