From 00da008d64e3e684d1b299cf7f59b155e73c19f6 Mon Sep 17 00:00:00 2001 From: Gani Georgiev Date: Fri, 1 Nov 2024 22:06:53 +0200 Subject: [PATCH] updated Store.GetOrSet to lock first with RLock/RUnlock --- tools/store/store.go | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/tools/store/store.go b/tools/store/store.go index f9c19d9f..9fd2096f 100644 --- a/tools/store/store.go +++ b/tools/store/store.go @@ -151,17 +151,19 @@ func (s *Store[T]) Set(key string, value T) { // GetOrSet retrieves a single existing value for the provided key // or stores a new one if it doesn't exist. func (s *Store[T]) GetOrSet(key string, setFunc func() T) T { - s.mu.Lock() - defer s.mu.Unlock() - - if s.data == nil { - s.data = make(map[string]T) - } - + // lock only reads to minimize locks contention + s.mu.RLock() v, ok := s.data[key] + s.mu.RUnlock() + if !ok { + s.mu.Lock() v = setFunc() + if s.data == nil { + s.data = make(map[string]T) + } s.data[key] = v + s.mu.Unlock() } return v