Skip to content

Commit

Permalink
add tests for loader singleflight
Browse files Browse the repository at this point in the history
  • Loading branch information
phuslu committed Jan 5, 2024
1 parent 0084daa commit 9185934
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
5 changes: 2 additions & 3 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,9 +135,8 @@ func (c *Cache[K, V]) getOrLoad(key K, loader func(K) (V, time.Duration, error),
if loader == nil {
return
}
value, err, ok = c.group.Do(key, func() (v V, err error) {
var ttl time.Duration
v, ttl, err = loader(key)
value, err, ok = c.group.Do(key, func() (V, error) {
v, ttl, err := loader(key)
if err != nil {
return v, err
}
Expand Down
29 changes: 29 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package lru
import (
"fmt"
"math/rand"
"sync"
"sync/atomic"
"testing"
"time"
)
Expand Down Expand Up @@ -163,6 +165,33 @@ func TestCacheLoader(t *testing.T) {
}
}

func TestCacheLoaderSingleflight(t *testing.T) {
var loads uint32

l := NewWithLoader[string, int](1024, func(key string) (int, time.Duration, error) {
atomic.AddUint32(&loads, 1)
time.Sleep(100 * time.Millisecond)
return int(key[0] - 'a' + 1), time.Hour, nil
})

var wg sync.WaitGroup
wg.Add(10)
for i := 0; i < 10; i++ {
go func(i int) {
defer wg.Done()
v, err, ok := l.GetOrLoad("a", nil)
if v != 1 || err != nil || !ok {
t.Errorf("a should be set to 1: %v,%v,%v", v, err, ok)
}
}(i)
}
wg.Wait()

if n := atomic.LoadUint32(&loads); n != 1 {
t.Errorf("a should be loaded only once: %v", n)
}
}

func TestCacheTouchGet(t *testing.T) {
l := newWithShards[string, int](1, 256)

Expand Down

0 comments on commit 9185934

Please sign in to comment.