goburrow / cache

Mango Cache 🥭 - Partial implementation of Guava Cache in Go (golang).
BSD 3-Clause "New" or "Revised" License
580 stars 48 forks source link

why sync call cache.Get() return different value #23

Closed justlazydog closed 3 years ago

justlazydog commented 3 years ago
func main() {
    c := cache.NewLoadingCache(func(key cache.Key) (cache.Value, error) {
        time.Sleep(time.Second)
        return a(), nil
    })
    fmt.Println(c.Get(1))
    fmt.Println(c.Get(1))
    fmt.Println(c.Get(1))
    fmt.Println(c.Get(1))
    fmt.Println(c.Get(1))
}

var count = 0

func a() int {
    count++
    return count
}

Output like this (expect value is always 1):

1 <nil>
2 <nil>
1 <nil>
1 <nil>
2 <nil>
nqv commented 3 years ago

The result from load function is put into the cache asynchronously so the behavior is undefined. I will fix

nqv commented 3 years ago

Can you try with the latest version

go get github.com/goburrow/cache@11fdd18bd87be12f122996e918e2909ddc1480b2
justlazydog commented 3 years ago

Can you try with the latest version

go get github.com/goburrow/cache@11fdd18bd87be12f122996e918e2909ddc1480b2

Thanks, the latest version works fine