Cache with blocking behavior
If multiple goroutines ask for the same key from the simple cache in the previous example, they may all decide to retrieve the object and put it back into the cache. That is inefficient. Usually, you would want one of those goroutines to retrieve the object while the other waits. This can be done using sync.Once
.
How to do it...
Cache elements are structures containing sync.Once
to ensure one goroutine gets the object while others wait for it. Also, the cache contains a Get
method that uses a getObjectFunc
callback to retrieve an object if it is not in the cache:
type cacheItem struct { sync.Once object *Object } type ObjectCache struct { mutex sync.RWMutex values map[string]*cacheItem getObjectFunc func(string) (*Object, error) } func NewObjectCache(getObjectFunc func(string) (*Object,error)) *ObjectCache { return &ObjectCache{ ...