MCPcopy
hub / github.com/caddyserver/caddy / LoadOrNew

Method LoadOrNew

usagepool.go:77–111  ·  view source on GitHub ↗

LoadOrNew loads the value associated with key from the pool if it already exists. If the key doesn't exist, it will call construct to create a new value and then stores that in the pool. An error is only returned if the constructor returns an error. The loaded or constructed value is returned. The l

(key any, construct Constructor)

Source from the content-addressed store, hash-verified

75// if the value already existed and was loaded, or false if it was
76// newly constructed.
77func (up *UsagePool) LoadOrNew(key any, construct Constructor) (value any, loaded bool, err error) {
78 var upv *usagePoolVal
79 up.Lock()
80 upv, loaded = up.pool[key]
81 if loaded {
82 upv.refs.Add(1)
83 up.Unlock()
84 upv.RLock()
85 value = upv.value
86 err = upv.err
87 upv.RUnlock()
88 } else {
89 upv = &usagePoolVal{}
90 upv.refs.Store(1)
91 upv.Lock()
92 up.pool[key] = upv
93 up.Unlock()
94 value, err = construct()
95 if err == nil {
96 upv.value = value
97 } else {
98 upv.err = err
99 up.Lock()
100 // this *should* be safe, I think, because we have a
101 // write lock on upv, but we might also need to ensure
102 // that upv.err is nil before doing this, since we
103 // released the write lock on up during construct...
104 // but then again it's also after midnight...
105 delete(up.pool, key)
106 up.Unlock()
107 }
108 upv.Unlock()
109 }
110 return value, loaded, err
111}
112
113// LoadOrStore loads the value associated with key from the pool if it
114// already exists, or stores it if it does not exist. It returns the

Callers 5

ListenQUICMethod · 0.80
openWriterMethod · 0.80
listenReusableFunction · 0.80
openDatabaseMethod · 0.80

Calls 1

AddMethod · 0.45

Tested by

no test coverage detected