aboutsummaryrefslogtreecommitdiffstats
path: root/android/onceper.go
diff options
context:
space:
mode:
authorColin Cross <ccross@android.com>2017-11-07 13:34:26 -0800
committerColin Cross <ccross@android.com>2017-11-07 13:36:44 -0800
commit99c6dfaecc2e0a2452a4142b533035aa52dbe6f2 (patch)
treea73fd39996767719dffbedb455a02c6baafe417c /android/onceper.go
parent5c9cf6eb84f3130b09f19e030ef95239d3cb7527 (diff)
downloadbuild_soong-99c6dfaecc2e0a2452a4142b533035aa52dbe6f2.tar.gz
build_soong-99c6dfaecc2e0a2452a4142b533035aa52dbe6f2.tar.bz2
build_soong-99c6dfaecc2e0a2452a4142b533035aa52dbe6f2.zip
Add OncePer.Get()
Allow functions to get the result associated with a OncePer key without also specifiying a function. Panics if the key has not already been set. Also replace the open-coded concurrent map implementation with the new sync.Map. Test: m checkbuild Change-Id: I814fdb1ffffaee8398dc877af146e29638c8a6a8
Diffstat (limited to 'android/onceper.go')
-rw-r--r--android/onceper.go33
1 files changed, 16 insertions, 17 deletions
diff --git a/android/onceper.go b/android/onceper.go
index 5f7a3102..f19f75c0 100644
--- a/android/onceper.go
+++ b/android/onceper.go
@@ -15,12 +15,12 @@
package android
import (
+ "fmt"
"sync"
- "sync/atomic"
)
type OncePer struct {
- values atomic.Value
+ values sync.Map
valuesLock sync.Mutex
}
@@ -29,33 +29,32 @@ type valueMap map[interface{}]interface{}
// Once computes a value the first time it is called with a given key per OncePer, and returns the
// value without recomputing when called with the same key. key must be hashable.
func (once *OncePer) Once(key interface{}, value func() interface{}) interface{} {
- // Atomically load the map without locking. If this is the first call Load() will return nil
- // and the type assertion will fail, leaving a nil map in m, but that's OK since m is only used
- // for reads.
- m, _ := once.values.Load().(valueMap)
- if v, ok := m[key]; ok {
+ // Fast path: check if the key is already in the map
+ if v, ok := once.values.Load(key); ok {
return v
}
+ // Slow path: lock so that we don't call the value function twice concurrently
once.valuesLock.Lock()
defer once.valuesLock.Unlock()
// Check again with the lock held
- m, _ = once.values.Load().(valueMap)
- if v, ok := m[key]; ok {
+ if v, ok := once.values.Load(key); ok {
return v
}
- // Copy the existing map
- newMap := make(valueMap, len(m))
- for k, v := range m {
- newMap[k] = v
- }
-
+ // Still not in the map, call the value function and store it
v := value()
+ once.values.Store(key, v)
+
+ return v
+}
- newMap[key] = v
- once.values.Store(newMap)
+func (once *OncePer) Get(key interface{}) interface{} {
+ v, ok := once.values.Load(key)
+ if !ok {
+ panic(fmt.Errorf("Get() called before Once()"))
+ }
return v
}