I am using io.prometheus.client.Gauge
to implement a thread safety counter to calculate the number of events processed in a time frame. Now there are several threads that are processing the events. And all can update the counter when it finishes the processing. My question ins is Gauge
counters are thread safety in nature? Following is my implementation.
private Map<String, Gauge> gaugeMap = new ConcurrentHashMap<>();
// This method will be called to register the Gauge
private void registerCounter(String metricName) {
Gauge gauge = Gauge.build()
.name(metricName)
.help(metricName)
.register(meterRegistry.getPrometheusRegistry());
gaugeMap.put(metricName, gauge);
}
public void incrementCounter(String metricName) {
if (isCounterPresent(metricName)) {
gaugeMap.get(metricName).inc();
}
}
public void incrementCounter(String metricName, long value) {
if (isCounterPresent(metricName)) {
gaugeMap.get(metricName).inc(value);
}
}
Following is my client code.
// on application startup I am calling registerCounter for all metrics
@PostConstruct
private void registerMetrics(List<String> metricList) {
// for each of metricList --> call registerCounter(String metricName)
}
Thread1
-------------------
// process N events
// call incrementCounter("metric-1", N);
Thread2
-------------------
// process N events
// call incrementCounter("metric-1", N);
Thread3
-------------------
// process N events
// call incrementCounter("metric-1", N);
Now my question is as multiple threads are incrementing the same counter, then will it give me the correct value?
Prometheus JVM Client README states that: