Cache computes duplicate work
Review this Go in-memory cache. Two goroutines may call GetOrCompute for the same key concurrently.
What a strong answer looks like
Separate real bugs from style. Rank issues by severity, point at the root cause rather than the symptom, and suggest a concrete fix, specific and kind.
0:00 of about 20 min
Mark a line and say what kind of problem it is.0 findings
1type Cache struct {
2 mu sync.RWMutex
3 data map[string]int
4}
5
6func (c *Cache) GetOrCompute(key string, compute func() int) int {
7 c.mu.RLock()
8 v, ok := c.data[key]
9 c.mu.RUnlock()
10 if ok {
11 return v
12 }
13 val := compute()
14 c.mu.Lock()
15 c.data[key] = val
16 c.mu.Unlock()
17 return val
18}
Which questions mattered is sealed until you submit. Telling you now would just be handing over the edge cases.
Run or narrate your approach, then ask the coach.