Skip to content

Commit

Permalink
Merge pull request #7 from samhendley/add-synchronization
Browse files Browse the repository at this point in the history
add synchronization around removeGauge/addGauge to avoid race condition
  • Loading branch information
rlazoti authored May 8, 2017
2 parents bdcc4ab + 003be44 commit 2c8bbad
Showing 1 changed file with 15 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,21 @@ object MetricsStatsReceiver {
}

private[metrics] case class MetricGauge(name: String)(f: => Float) extends Gauge {
// remove old gauge's value before adding a new one
metrics.getGauges(new MetricFilter() {
override def matches(metricName: String, metric: Metric): Boolean =
metricName == name
}).asScala
.foreach { case (gaugeName, _) => metrics.remove(gaugeName) }

metrics.register(name, new MGauge[Float]() {
override def getValue(): Float = f
})
// we need to synchronize so this is safe with multiple threads. Ideally the callers are themselves
// synchronized so they don't overwrite each others gauges but until they are we should protect
// ourselves from that race condition.
synchronized {
// remove old gauge's value before adding a new one
metrics.getGauges(new MetricFilter() {
override def matches(metricName: String, metric: Metric): Boolean =
metricName == name
}).asScala
.foreach { case (gaugeName, _) => metrics.remove(gaugeName) }

metrics.register(name, new MGauge[Float]() {
override def getValue(): Float = f
})
}

override def remove(): Unit = metrics.remove(name)
}
Expand Down

0 comments on commit 2c8bbad

Please sign in to comment.