1 /* 2 Copyright 2023 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package synctrack 18 19 import ( 20 "sync" 21 "sync/atomic" 22 ) 23 24 // Lazy defers the computation of `Evaluate` to when it is necessary. It is 25 // possible that Evaluate will be called in parallel from multiple goroutines. 26 type Lazy[T any] struct { 27 Evaluate func() (T, error) 28 29 cache atomic.Pointer[cacheEntry[T]] 30 } 31 32 type cacheEntry[T any] struct { 33 eval func() (T, error) 34 lock sync.RWMutex 35 result *T 36 } 37 38 func (e *cacheEntry[T]) get() (T, error) { 39 if cur := func() *T { 40 e.lock.RLock() 41 defer e.lock.RUnlock() 42 return e.result 43 }(); cur != nil { 44 return *cur, nil 45 } 46 47 e.lock.Lock() 48 defer e.lock.Unlock() 49 if e.result != nil { 50 return *e.result, nil 51 } 52 r, err := e.eval() 53 if err == nil { 54 e.result = &r 55 } 56 return r, err 57 } 58 59 func (z *Lazy[T]) newCacheEntry() *cacheEntry[T] { 60 return &cacheEntry[T]{eval: z.Evaluate} 61 } 62 63 // Notify should be called when something has changed necessitating a new call 64 // to Evaluate. 65 func (z *Lazy[T]) Notify() { z.cache.Swap(z.newCacheEntry()) } 66 67 // Get should be called to get the current result of a call to Evaluate. If the 68 // current cached value is stale (due to a call to Notify), then Evaluate will 69 // be called synchronously. If subsequent calls to Get happen (without another 70 // Notify), they will all wait for the same return value. 71 // 72 // Error returns are not cached and will cause multiple calls to evaluate! 73 func (z *Lazy[T]) Get() (T, error) { 74 e := z.cache.Load() 75 if e == nil { 76 // Since we don't force a constructor, nil is a possible value. 77 // If multiple Gets race to set this, the swap makes sure only 78 // one wins. 79 z.cache.CompareAndSwap(nil, z.newCacheEntry()) 80 e = z.cache.Load() 81 } 82 return e.get() 83 } 84