-
Notifications
You must be signed in to change notification settings - Fork 125
Description
I have some items whose values are very expensive to initialize. I want to initialize each of them on the first read of the corresponding key and then cache indefinitely (unless evicted due to cache size). I also want to do this atomically in such way that reads and writes to other keys in the cache can proceed while the expensive initialization occurs, but each value is initialized at most once.
I can work around the fact that the initialization is slow by setting a placeholder value with a mutex that will be released once the initialization is complete.
What I can't figure out how to do with this API is the atomic Get/Set (without using additional locks). Would you be open to adding a TrackingGetOrSet(key string, defaultValue interface{}, duration time.Duration) (item TrackingItem item, didSet bool) method which atomically gets the key if found, or sets it to the new value if not? By looking at the code it seems fairly straightforward to implement as it can occur inside a bucket's RWMutex.
That said I can see it's a pretty specific request. I'm happy to make a PR.
PS: Is there a race condition in TrackingGet? It seems like the item could be removed from the cache between the get() and the track() calls... But maybe I'm missing something?
Thanks!