Jelajahi Sumber

Unlock Registry mutex even in case of panic.

Alexey Palazhchenko 13 tahun lalu
induk
melakukan
a40b686b9b
1 mengubah file dengan 7 tambahan dan 9 penghapusan
  1. 7 9
      registry.go

+ 7 - 9
registry.go

@@ -15,8 +15,7 @@ type Registry interface {
 	Unregister(string)
 }
 
-// The standard implementation of a Registry is a set of mutex-protected
-// maps of names to metrics.
+// The standard implementation of a Registry is a mutex-protected mapping of names to metrics.
 type StandardRegistry struct {
 	mutex   *sync.Mutex
 	metrics map[string]interface{}
@@ -33,18 +32,17 @@ func NewRegistry() *StandardRegistry {
 // Call the given function for each registered metric.
 func (r *StandardRegistry) Each(f func(string, interface{})) {
 	r.mutex.Lock()
+	defer r.mutex.Unlock()
 	for name, i := range r.metrics {
 		f(name, i)
 	}
-	r.mutex.Unlock()
 }
 
 // Get the metric by the given name or nil if none is registered.
 func (r *StandardRegistry) Get(name string) interface{} {
 	r.mutex.Lock()
-	i := r.metrics[name]
-	r.mutex.Unlock()
-	return i
+	defer r.mutex.Unlock()
+	return r.metrics[name]
 }
 
 // Register the given metric under the given name.
@@ -52,25 +50,25 @@ func (r *StandardRegistry) Register(name string, i interface{}) {
 	switch i.(type) {
 	case Counter, Gauge, Healthcheck, Histogram, Meter, Timer:
 		r.mutex.Lock()
+		defer r.mutex.Unlock()
 		r.metrics[name] = i
-		r.mutex.Unlock()
 	}
 }
 
 // Run all registered healthchecks.
 func (r *StandardRegistry) RunHealthchecks() {
 	r.mutex.Lock()
+	defer r.mutex.Unlock()
 	for _, i := range r.metrics {
 		if h, ok := i.(Healthcheck); ok {
 			h.Check()
 		}
 	}
-	r.mutex.Unlock()
 }
 
 // Unregister the metric with the given name.
 func (r *StandardRegistry) Unregister(name string) {
 	r.mutex.Lock()
+	defer r.mutex.Unlock()
 	delete(r.metrics, name)
-	r.mutex.Unlock()
 }