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

GetOrSet method to handle case for atomic get and set if not exists #117

Open technicianted opened 4 years ago

technicianted commented 4 years ago

This PR adds a new method GetOrSet to handle the case where we run into a race when multiple threads do "if not found then set" sequence. Without using GetOrSet, callers will have to use global locks, then perform 1-2 cache operations (Add followed by Get if already exists) which would be redundant and inefficient.

There was a similar PR #82 but it tried to do it using a closure instead of a simple value. This PR takes a much simpler approach to avoid potential long held locks by external code.