lazy.go 2.2 KB

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