From 46ee3e4d49fa5cf6ada56f8ddeba7b256221c069 Mon Sep 17 00:00:00 2001 From: Corentin Chary Date: Fri, 13 Nov 2015 15:36:55 +0100 Subject: [PATCH] Add set() to Counters. While it should generally not be used, having a set() method for counters is this only way to relay counters from other monitoring systems. It was implemented in the golang client for the same reasons. --- .../java/io/prometheus/client/Counter.java | 23 +++++++++++++++++++ .../io/prometheus/client/CounterTest.java | 10 +++++++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/simpleclient/src/main/java/io/prometheus/client/Counter.java b/simpleclient/src/main/java/io/prometheus/client/Counter.java index bc0ec155a..4a0038b3c 100644 --- a/simpleclient/src/main/java/io/prometheus/client/Counter.java +++ b/simpleclient/src/main/java/io/prometheus/client/Counter.java @@ -113,6 +113,23 @@ public void inc(double amt) { } value.add(amt); } + /** + * Set is used to set the Counter to an arbitrary value. It is only used + * if you have to transfer a value from an external counter into this + * Prometheus metric. Do not use it for regular handling of a + * Prometheus counter (as it can be used to break the contract of + * monotonically increasing values). + * @param value + */ + public void set(double val) { + synchronized(this) { + value.reset(); + // If get() were called here it'd see an invalid value, so use a lock. + // inc()/dec() don't need locks, as all the possible outcomes + // are still possible if set() were atomic so no new races are introduced. + value.add(val); + } + } /** * Get the value of the counter. */ @@ -135,6 +152,12 @@ public void inc() { public void inc(double amt) { noLabelsChild.inc(amt); } + /** + * Set the gauge with no labels to the given value. + */ + public void set(double val) { + noLabelsChild.set(val); + } @Override public List collect() { diff --git a/simpleclient/src/test/java/io/prometheus/client/CounterTest.java b/simpleclient/src/test/java/io/prometheus/client/CounterTest.java index 97642c0bf..03e5b3e60 100644 --- a/simpleclient/src/test/java/io/prometheus/client/CounterTest.java +++ b/simpleclient/src/test/java/io/prometheus/client/CounterTest.java @@ -34,7 +34,15 @@ public void testIncrement() { noLabels.labels().inc(); assertEquals(8.0, getValue(), .001); } - + + @Test + public void testSet() { + noLabels.set(42); + assertEquals(42, getValue(), .001); + noLabels.labels().set(7); + assertEquals(7.0, getValue(), .001); + } + @Test(expected=IllegalArgumentException.class) public void testNegativeIncrementFails() { noLabels.inc(-1);