muesli / cache2go

Concurrency-safe Go caching library with expiration capabilities and access counters
Other
2.11k stars 515 forks source link

Why creating a Cache requires Double check whether the table exists or not. #47

Closed CoolLiuzw closed 4 years ago

CoolLiuzw commented 4 years ago
// Cache returns the existing cache table with given name or creates a new one
// if the table does not exist yet.
func Cache(table string) *CacheTable {
    mutex.RLock()
    t, ok := cache[table]
    mutex.RUnlock()

    if !ok {
        mutex.Lock()
        t, ok = cache[table]
        // Double check whether the table exists or not.
        if !ok {
            t = &CacheTable{
                name:  table,
                items: make(map[interface{}]*CacheItem),
            }
            cache[table] = t
        }
        mutex.Unlock()
    }

    return t
}
CoolLiuzw commented 4 years ago