2014-12-09 12:29:25 +08:00
|
|
|
package util
|
|
|
|
|
2015-01-08 15:54:50 +08:00
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
)
|
2014-12-09 12:29:25 +08:00
|
|
|
|
|
|
|
// A mostly for read map, which can thread-safely
|
|
|
|
// initialize the map entries.
|
|
|
|
type ConcurrentReadMap struct {
|
|
|
|
rmutex sync.RWMutex
|
|
|
|
Items map[string]interface{}
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewConcurrentReadMap() *ConcurrentReadMap {
|
|
|
|
return &ConcurrentReadMap{Items: make(map[string]interface{})}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *ConcurrentReadMap) initMapEntry(key string, newEntry func() interface{}) (value interface{}) {
|
2016-04-11 15:53:59 +08:00
|
|
|
m.rmutex.Lock()
|
|
|
|
defer m.rmutex.Unlock()
|
2014-12-09 12:29:25 +08:00
|
|
|
if value, ok := m.Items[key]; ok {
|
|
|
|
return value
|
|
|
|
}
|
|
|
|
value = newEntry()
|
|
|
|
m.Items[key] = value
|
|
|
|
return value
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *ConcurrentReadMap) Get(key string, newEntry func() interface{}) interface{} {
|
|
|
|
m.rmutex.RLock()
|
|
|
|
if value, ok := m.Items[key]; ok {
|
|
|
|
m.rmutex.RUnlock()
|
|
|
|
return value
|
|
|
|
}
|
2015-03-10 15:20:31 +08:00
|
|
|
m.rmutex.RUnlock()
|
|
|
|
return m.initMapEntry(key, newEntry)
|
2014-12-09 12:29:25 +08:00
|
|
|
}
|