Skip to content

Commit

Permalink
[chore] make sharedcomponent Map threadsafe (#9170)
Browse files Browse the repository at this point in the history
**Description:**
Add just enough code to make sharedcomponent Map thread safe.

**Link to tracking Issue:**
Relates to #9156

Follow up to #9157, should be reviewed after it is merged.
  • Loading branch information
atoulme authored Jan 9, 2024
1 parent fbfbe04 commit 6a726c9
Showing 1 changed file with 5 additions and 0 deletions.
5 changes: 5 additions & 0 deletions internal/sharedcomponent/sharedcomponent.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,15 @@ func NewMap[K comparable, V component.Component]() *Map[K, V] {

// Map keeps reference of all created instances for a given shared key such as a component configuration.
type Map[K comparable, V component.Component] struct {
lock sync.Mutex
components map[K]*Component[V]
}

// LoadOrStore returns the already created instance if exists, otherwise creates a new instance
// and adds it to the map of references.
func (m *Map[K, V]) LoadOrStore(key K, create func() (V, error), telemetrySettings *component.TelemetrySettings) (*Component[V], error) {
m.lock.Lock()
defer m.lock.Unlock()
if c, ok := m.components[key]; ok {
// If we haven't already seen this telemetry settings, this shared component represents
// another instance. Wrap ReportStatus to report for all instances this shared
Expand All @@ -49,6 +52,8 @@ func (m *Map[K, V]) LoadOrStore(key K, create func() (V, error), telemetrySettin
newComp := &Component[V]{
component: comp,
removeFunc: func() {
m.lock.Lock()
defer m.lock.Unlock()
delete(m.components, key)
},
telemetry: telemetrySettings,
Expand Down

0 comments on commit 6a726c9

Please sign in to comment.