GetOrSet retrieves a single existing value for the provided key or stores a new one if it doesn't exist.
(key K, setFunc func() T)
| 174 | // GetOrSet retrieves a single existing value for the provided key |
| 175 | // or stores a new one if it doesn't exist. |
| 176 | func (s *Store[K, T]) GetOrSet(key K, setFunc func() T) T { |
| 177 | // lock only reads to minimize locks contention |
| 178 | s.mu.RLock() |
| 179 | v, ok := s.data[key] |
| 180 | s.mu.RUnlock() |
| 181 | if ok { |
| 182 | return v |
| 183 | } |
| 184 | |
| 185 | // lock again for write |
| 186 | s.mu.Lock() |
| 187 | defer s.mu.Unlock() |
| 188 | |
| 189 | // check again in case it was set between the 2 locks |
| 190 | v, ok = s.data[key] |
| 191 | if !ok { |
| 192 | v = setFunc() |
| 193 | if s.data == nil { |
| 194 | s.data = make(map[K]T) |
| 195 | } |
| 196 | s.data[key] = v |
| 197 | } |
| 198 | |
| 199 | return v |
| 200 | } |
| 201 | |
| 202 | // SetIfLessThanLimit sets (or overwrite if already exist) a new value for key. |
| 203 | // |
no outgoing calls