From 05666f1de64aa6dbb2516df8caa6359f81b03e6a Mon Sep 17 00:00:00 2001 From: Matt Gleich Date: Sun, 29 Dec 2024 04:49:43 -0500 Subject: [PATCH] feat: optimize mutex locks in cache updates Signed-off-by: Matt Gleich --- internal/cache/cache.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/internal/cache/cache.go b/internal/cache/cache.go index 2bc1c57..81871a4 100644 --- a/internal/cache/cache.go +++ b/internal/cache/cache.go @@ -64,23 +64,25 @@ func (c *Cache[T]) ServeHTTP() http.HandlerFunc { func (c *Cache[T]) Update(data T) { var updated bool - c.dataMutex.Lock() + c.dataMutex.RLock() old, err := json.Marshal(c.data) if err != nil { lumber.Error(err, "failed to json marshal old data") return } + c.dataMutex.RUnlock() new, err := json.Marshal(data) if err != nil { lumber.Error(err, "failed to json marshal new data") return } if string(old) != string(new) && string(new) != "null" && strings.Trim(string(new), " ") != "" { + c.dataMutex.Lock() c.data = data c.updated = time.Now() + c.dataMutex.Unlock() updated = true } - c.dataMutex.Unlock() if updated { c.persistToFile()