-
Notifications
You must be signed in to change notification settings - Fork 9
feat: use atomic pointer for global feature flag client #332
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this is good, but we should replace it with an atomic ptr in the future.
we also need to improve testability of featureflags which is kinda messy right now.
I think the only reason there's a lock here is because there's a |
Did a quick benchmark: var globalLock sync.RWMutex
var globalClient Client = MockClient{}
// See https://blog.dubbelboer.com/2015/08/23/rwmutex-vs-atomicvalue-vs-unsafepointer.html
var globalLockAtomic = atomic.NewUnsafePointer(unsafe.Pointer(&globalClient))
func SetGlobalClient(client Client) {
if client == nil {
return
}
globalLock.Lock()
globalClient = client
globalLock.Unlock()
globalLockAtomic.Store(unsafe.Pointer(&client))
}
func GetGlobalClient() Client {
globalLock.RLock()
defer globalLock.RUnlock()
return globalClient
}
func GetGlobalClientAtomic() Client {
c := (*Client)(globalLockAtomic.Load())
return *c
}
func BenchmarkGlobalAccess(b *testing.B) {
SetGlobalClient(&ldClient{})
var c1, c2 Client
b.Run("rwmutex", func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
c1 = GetGlobalClient()
}
})
b.Run("atomic", func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
c2 = GetGlobalClientAtomic()
}
})
require.Equal(b, c1, c2)
}
Take this with a grain of salt, because there's no contention. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
i don't think the dependency on the atomic lib from uber is needed but i don't care a lot
@cbosss wanna ship this? |
Use an
rwmutexatomic pointer when accessing the global featureflag client.