Skip to content

Commit

Permalink
feat: optimize mutex locks in cache updates
Browse files Browse the repository at this point in the history
Signed-off-by: Matt Gleich <[email protected]>
  • Loading branch information
gleich committed Dec 29, 2024
1 parent 3ff72ea commit 05666f1
Showing 1 changed file with 4 additions and 2 deletions.
6 changes: 4 additions & 2 deletions internal/cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down

0 comments on commit 05666f1

Please sign in to comment.