From 69e59822f09d1d958fb190f59191b73441f59ecd Mon Sep 17 00:00:00 2001 From: siddharth ravikumar Date: Mon, 26 Dec 2022 16:40:40 -0500 Subject: cache: make it concurrency safe --- cache/cache_test.go | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) (limited to 'cache/cache_test.go') diff --git a/cache/cache_test.go b/cache/cache_test.go index 4751260..c663abf 100644 --- a/cache/cache_test.go +++ b/cache/cache_test.go @@ -5,6 +5,7 @@ package cache import ( "bytes" + "fmt" "testing" "time" ) @@ -71,3 +72,45 @@ func TestCacheGet(t *testing.T) { return } } + +func TestConcurrentSets(t *testing.T) { + // Expiration time for all keys. + exp := time.Now().Add(time.Second * 120) + + // Generate some keys. + keys := make([]string, 0) + maxKeys := 1000 + for i := 0; i < maxKeys; i++ { + keys = append(keys, fmt.Sprintf("key-%d", i)) + } + + // Go routing for adding keys to cache. + addToCache := func(c *Cache, keys []string, donec chan int) { + for i := 0; i < len(keys); i++ { + c.Set(keys[i], []byte(fmt.Sprintf("val-%d", i)), exp) + } + donec <- 1 + } + + // Init. cache. + c := NewCache() + if c == nil { + t.Errorf("cache is nil") + return + } + donec := make(chan int) + + // Add keys to cache concurrently. + go addToCache(c, keys, donec) + go addToCache(c, keys, donec) + go addToCache(c, keys, donec) + completed := 0 + for completed < 3 { + <-donec + completed += 1 + } + + if len(c.store) != maxKeys { + t.Errorf("number of keys in store != %d: %v", maxKeys, c.store) + } +} -- cgit v1.2.3