Skip to content

Commit

Permalink
Fix another race condition.
Browse files Browse the repository at this point in the history
  • Loading branch information
sbruens committed Aug 19, 2024
1 parent 2f5077e commit feb30b6
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 14 deletions.
34 changes: 20 additions & 14 deletions cmd/outline-ss-server/lru_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,22 +49,28 @@ func NewLRUCache[K comparable, V any](capacity int, duration time.Duration, clea

func (c *LRUCache[K, V]) Get(key K) (V, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
elem, ok := c.items[key]
if !ok {
c.mu.RUnlock()
var zero V
return zero, false
}
ent := elem.Value.(*entry[K, V])
c.mu.RUnlock()

if elem, ok := c.items[key]; ok {
c.lru.MoveToFront(elem)
ent := elem.Value.(*entry[K, V])
if time.Since(ent.lastAccess) > c.duration {
c.lru.Remove(elem)
delete(c.items, key)
var zero V
return zero, false
}
ent.lastAccess = time.Now()
return ent.value, true
c.mu.Lock()
defer c.mu.Unlock()

if time.Since(ent.lastAccess) > c.duration {
c.lru.Remove(elem)
delete(c.items, key)
var zero V
return zero, false
}
var zero V
return zero, false

c.lru.MoveToFront(elem)
ent.lastAccess = time.Now()
return ent.value, true
}

func (c *LRUCache[K, V]) Set(key K, value V) {
Expand Down
28 changes: 28 additions & 0 deletions cmd/outline-ss-server/lru_cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
package main

import (
"math/rand"
"sync"
"testing"
"time"

Expand Down Expand Up @@ -76,3 +78,29 @@ func TestLRUCache(t *testing.T) {
cache.StopCleanup()
})
}

func BenchmarkLRUCache(b *testing.B) {
cache := NewLRUCache[int, int](1000, time.Minute, time.Minute)

keys := make([]int, b.N)
for i := 0; i < b.N; i++ {
keys[i] = rand.Intn(2000)
}

b.ResetTimer()

var wg sync.WaitGroup
for i := 0; i < b.N; i++ {
wg.Add(1)
go func(key int) {
defer wg.Done()
cache.Get(key)
if rand.Intn(2) == 0 {
cache.Set(key, rand.Int())
}
}(keys[i])
}
wg.Wait()

cache.StopCleanup()
}

0 comments on commit feb30b6

Please sign in to comment.