From 68b746edea11c5bc9862b1efce47928b0015bf1d Mon Sep 17 00:00:00 2001 From: oabrivard Date: Mon, 21 Aug 2023 15:45:43 +0200 Subject: [PATCH] Solved 2-race-in-cache --- 2-race-in-cache/main.go | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/2-race-in-cache/main.go b/2-race-in-cache/main.go index b28abd7..cbfecb4 100644 --- a/2-race-in-cache/main.go +++ b/2-race-in-cache/main.go @@ -8,7 +8,12 @@ package main -import "container/list" +import ( + "container/list" + "sync" +) + +var mu sync.Mutex // CacheSize determines how big the cache can grow const CacheSize = 100 @@ -41,12 +46,18 @@ func New(load KeyStoreCacheLoader) *KeyStoreCache { // Get gets the key from cache, loads it from the source if needed func (k *KeyStoreCache) Get(key string) string { + mu.Lock() + defer mu.Unlock() + if e, ok := k.cache[key]; ok { k.pages.MoveToFront(e) - return e.Value.(page).Value + value := e.Value.(page).Value + return value } + // Miss - load from database and save it in cache p := page{key, k.load(key)} + // if cache is full remove the least used item if len(k.cache) >= CacheSize { end := k.pages.Back() @@ -57,6 +68,7 @@ func (k *KeyStoreCache) Get(key string) string { } k.pages.PushFront(p) k.cache[key] = k.pages.Front() + return p.Value }