go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/sync/promise/map.go (about) 1 // Copyright 2018 The LUCI Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package promise 16 17 import ( 18 "context" 19 "sync" 20 ) 21 22 // Map is a map from some key to a promise that does something associated 23 // with this key. 24 // 25 // First call to Get initiates a new promise. All subsequent calls return exact 26 // same promise (even if it has finished). 27 type Map struct { 28 mu sync.RWMutex 29 m map[any]*Promise 30 } 31 32 // Get either returns an existing promise for the given key or creates and 33 // immediately launches a new promise. 34 func (pm *Map) Get(ctx context.Context, key any, gen Generator) *Promise { 35 pm.mu.RLock() 36 p := pm.m[key] 37 pm.mu.RUnlock() 38 39 if p != nil { 40 return p 41 } 42 43 pm.mu.Lock() 44 defer pm.mu.Unlock() 45 46 if p = pm.m[key]; p == nil { 47 p = New(ctx, gen) 48 if pm.m == nil { 49 pm.m = make(map[any]*Promise, 1) 50 } 51 pm.m[key] = p 52 } 53 return p 54 }