Browse Source

MINOR: Add method `hasMetrics()` to class `Sensor` (#7692)

Sometimes to be backwards compatible regarding metrics the simplest
solution is to create an empty sensor. Recording an empty sensor on
the hot path may negatively impact performance. With hasMetrics()
recordings of empty sensors on the hot path can be avoided without
being to invasive.

Reviewers: Bill Bejeck <bbejeck@gmail.com>
pull/7288/merge
Bruno Cadonna 5 years ago committed by Bill Bejeck
parent
commit
898ad8271a
  1. 9
      clients/src/main/java/org/apache/kafka/common/metrics/Sensor.java
  2. 27
      clients/src/test/java/org/apache/kafka/common/metrics/SensorTest.java

9
clients/src/main/java/org/apache/kafka/common/metrics/Sensor.java

@ -288,6 +288,15 @@ public final class Sensor { @@ -288,6 +288,15 @@ public final class Sensor {
}
}
/**
* Return if metrics were registered with this sensor.
*
* @return true if metrics were registered, false otherwise
*/
public synchronized boolean hasMetrics() {
return !metrics.isEmpty();
}
/**
* Return true if the Sensor is eligible for removal due to inactivity.
* false otherwise

27
clients/src/test/java/org/apache/kafka/common/metrics/SensorTest.java

@ -18,6 +18,7 @@ package org.apache.kafka.common.metrics; @@ -18,6 +18,7 @@ package org.apache.kafka.common.metrics;
import org.apache.kafka.common.MetricName;
import org.apache.kafka.common.metrics.stats.Avg;
import org.apache.kafka.common.metrics.stats.CumulativeCount;
import org.apache.kafka.common.metrics.stats.Meter;
import org.apache.kafka.common.metrics.stats.Rate;
import org.apache.kafka.common.metrics.stats.WindowedSum;
@ -39,6 +40,8 @@ import java.util.concurrent.Executors; @@ -39,6 +40,8 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
@ -184,4 +187,26 @@ public class SensorTest { @@ -184,4 +187,26 @@ public class SensorTest {
}
}
}
}
@Test
public void shouldReturnPresenceOfMetrics() {
final Metrics metrics = new Metrics();
final Sensor sensor = metrics.sensor("sensor");
assertThat(sensor.hasMetrics(), is(false));
sensor.add(
new MetricName("name1", "group1", "description1", Collections.emptyMap()),
new WindowedSum()
);
assertThat(sensor.hasMetrics(), is(true));
sensor.add(
new MetricName("name2", "group2", "description2", Collections.emptyMap()),
new CumulativeCount()
);
assertThat(sensor.hasMetrics(), is(true));
}
}
Loading…
Cancel
Save