Skip to content

Commit c5ec0df

Browse files
fix: provide synchronization for Notification Center Cache (#273)
* fix: provide synchronization for Notification Center Cache
1 parent f76e35e commit c5ec0df

File tree

2 files changed

+19
-6
lines changed

2 files changed

+19
-6
lines changed

pkg/registry/service.go

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,21 @@
1818
package registry
1919

2020
import (
21+
"sync"
22+
2123
"github.com/optimizely/go-sdk/pkg/notification"
2224
)
2325

2426
var notificationCenterCache = make(map[string]notification.Center)
27+
var notificationLock sync.Mutex
2528

2629
// GetNotificationCenter returns the notification center instance associated with the given SDK Key or creates a new one if not found
2730
func GetNotificationCenter(sdkKey string) notification.Center {
28-
var notificationCenter notification.Center
29-
var ok bool
30-
if notificationCenter, ok = notificationCenterCache[sdkKey]; !ok {
31+
notificationLock.Lock()
32+
defer notificationLock.Unlock()
33+
34+
notificationCenter, ok := notificationCenterCache[sdkKey]
35+
if !ok {
3136
notificationCenter = notification.NewNotificationCenter()
3237
notificationCenterCache[sdkKey] = notificationCenter
3338
}

pkg/registry/service_test.go

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,19 @@ type ServiceRegistryTestSuite struct {
2828

2929
func (s *ServiceRegistryTestSuite) TestGetNotificationCenter() {
3030
// empty state, make sure we get a new notification center
31-
sdkKey := "sdk_key_1"
32-
notificationCenter := GetNotificationCenter(sdkKey)
31+
sdkKey1 := "sdk_key_1"
32+
sdkKey2 := "sdk_key_2"
33+
notificationCenter := GetNotificationCenter(sdkKey1)
3334
s.NotNil(notificationCenter)
3435

35-
notificationCenter2 := GetNotificationCenter(sdkKey)
36+
notificationCenter2 := GetNotificationCenter(sdkKey1)
37+
s.Equal(notificationCenter, notificationCenter2)
38+
39+
// make sure sdkKey2 does not cause race condition
40+
notificationCenter = GetNotificationCenter(sdkKey2)
41+
s.NotNil(notificationCenter)
42+
43+
notificationCenter2 = GetNotificationCenter(sdkKey2)
3644
s.Equal(notificationCenter, notificationCenter2)
3745
}
3846

0 commit comments

Comments
 (0)