Skip to content

Commit

Permalink
Merge pull request #392 from weibocom/fix/metrics_lock
Browse files Browse the repository at this point in the history
Optimize metrics lock release
  • Loading branch information
rayzhang0603 authored Mar 28, 2024
2 parents af7c115 + 3a3730a commit 4f95c41
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 24 deletions.
62 changes: 39 additions & 23 deletions metrics/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,20 +106,11 @@ type StatWriter interface {

func GetOrRegisterStatItem(group, groupSuffix string, service string) StatItem {
k := group + groupSuffix + service
itemsLock.RLock()
item := items[k]
itemsLock.RUnlock()
item := safeGet(k)
if item != nil {
return item
}
itemsLock.Lock()
item = items[k]
if item == nil {
item = NewStatItem(group, groupSuffix, service)
items[k] = item
}
itemsLock.Unlock()
return item
return safePutAbsent(k, group, groupSuffix, service)
}

func GetStatItem(group, groupSuffix string, service string) StatItem {
Expand All @@ -134,22 +125,16 @@ func NewDefaultStatItem(group, groupSuffix string, service string) StatItem {
}

func RMStatItem(group, groupSuffix string, service string) {
itemsLock.RLock()
i := items[group+groupSuffix+service]
itemsLock.RUnlock()
if i != nil {
i.Clear()
itemsLock.Lock()
delete(items, group+groupSuffix+service)
itemsLock.Unlock()
k := group + groupSuffix + service
item := safeGet(k)
if item != nil {
safeDelete(k)
item.Clear()
}
}

func ClearStatItems() {
itemsLock.Lock()
old := items
items = make(map[string]StatItem, 64)
itemsLock.Unlock()
old := safeExchangeNew()
for _, item := range old {
item.Clear()
}
Expand All @@ -173,6 +158,37 @@ func StatItemSize() int {
return len(items)
}

func safeGet(k string) StatItem {
itemsLock.RLock()
defer itemsLock.RUnlock()
return items[k]
}

func safePutAbsent(k, group, groupSuffix, service string) StatItem {
itemsLock.Lock()
defer itemsLock.Unlock()
item := items[k]
if item == nil {
item = NewStatItem(group, groupSuffix, service)
items[k] = item
}
return item
}

func safeDelete(k string) {
itemsLock.Lock()
defer itemsLock.Unlock()
delete(items, k)
}

func safeExchangeNew() map[string]StatItem {
itemsLock.Lock()
defer itemsLock.Unlock()
old := items
items = make(map[string]StatItem, 64)
return old
}

// Escape the string avoid invalid graphite key
func Escape(s string) string {
if v, ok := escapeCache.Load(s); ok {
Expand Down
2 changes: 1 addition & 1 deletion protocol/motanProtocol.go
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,7 @@ func DecodeWithTime(reader *bufio.Reader, buf *[]byte, maxContentLength int) (ms
// get a message from pool
msg = AcquireMessage()
defer func() {
if err != nil {
if err != nil && msg != nil {
msg.SetCanRelease()
ReleaseMessage(msg)
}
Expand Down

0 comments on commit 4f95c41

Please sign in to comment.