Skip to content

Commit

Permalink
chore: optimize lock in discov.etcd (#4275)
Browse files Browse the repository at this point in the history
  • Loading branch information
kevwan committed Jul 27, 2024
1 parent 0e61303 commit caf0e64
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions core/discov/internal/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ var (
// A Registry is a registry that manages the etcd client connections.
type Registry struct {
clusters map[string]*cluster
lock sync.Mutex
lock sync.RWMutex
}

// GetRegistry returns a global Registry.
Expand Down Expand Up @@ -60,12 +60,19 @@ func (r *Registry) Monitor(endpoints []string, key string, l UpdateListener) err

func (r *Registry) getCluster(endpoints []string) (c *cluster, exists bool) {
clusterKey := getClusterKey(endpoints)
r.lock.Lock()
defer r.lock.Unlock()
r.lock.RLock()
c, exists = r.clusters[clusterKey]
r.lock.RUnlock()

if !exists {
c = newCluster(endpoints)
r.clusters[clusterKey] = c
r.lock.Lock()
defer r.lock.Unlock()
// double-check locking
c, exists = r.clusters[clusterKey]
if !exists {
c = newCluster(endpoints)
r.clusters[clusterKey] = c
}
}

return
Expand Down

0 comments on commit caf0e64

Please sign in to comment.