Core instrumentation library for the Prometheus Java client, providing fundamental metric types for application monitoring
—
Histogram metrics track distributions of values like request latencies, response sizes, or processing times by organizing observations into configurable buckets. They provide count, sum, and bucket data for calculating percentiles and distributions.
Create histogram metrics using the builder pattern with configurable bucket boundaries.
/**
* Create a new Histogram builder with default buckets
* @return Builder instance for configuration
*/
public static Histogram.Builder build();
/**
* Create a new Histogram builder with required fields
* @param name The metric name (without _bucket/_count/_sum suffixes)
* @param help The help text describing the metric
* @return Builder instance for configuration
*/
public static Histogram.Builder build(String name, String help);Usage Example:
import io.prometheus.client.Histogram;
// Basic histogram with default buckets
Histogram requestDuration = Histogram.build()
.name("request_duration_seconds")
.help("Request duration in seconds")
.register();
// Histogram with custom buckets
Histogram responseSizes = Histogram.build()
.name("response_size_bytes")
.help("HTTP response sizes")
.buckets(.01, .05, .1, .25, .5, 1, 2.5, 5, 10)
.register();Configure histogram bucket boundaries and exemplar support.
public static class Builder extends SimpleCollector.Builder<Builder, Histogram> {
/**
* Set custom bucket boundaries
* @param buckets Upper bounds for buckets (must be in increasing order)
* @return Builder for method chaining
* @throws IllegalStateException if buckets not in increasing order
*/
public Builder buckets(double... buckets);
/**
* Generate linear bucket sequence
* @param start First bucket upper bound
* @param width Width between buckets
* @param count Number of buckets to generate
* @return Builder for method chaining
*/
public Builder linearBuckets(double start, double width, int count);
/**
* Generate exponential bucket sequence
* @param start First bucket upper bound
* @param factor Multiplication factor between buckets
* @param count Number of buckets to generate
* @return Builder for method chaining
*/
public Builder exponentialBuckets(double start, double factor, int count);
/**
* Enable exemplar support with default sampler
* @return Builder for method chaining
*/
public Builder withExemplars();
/**
* Disable exemplar support
* @return Builder for method chaining
*/
public Builder withoutExemplars();
/**
* Configure custom exemplar sampler
* @param exemplarSampler Custom sampler implementation
* @return Builder for method chaining
*/
public Builder withExemplarSampler(HistogramExemplarSampler exemplarSampler);
}Usage Examples:
// Custom bucket configuration
Histogram latencyHistogram = Histogram.build()
.name("api_latency_seconds")
.help("API request latency")
.buckets(0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0)
.register();
// Linear buckets: 10, 20, 30, 40, 50 milliseconds
Histogram processingTime = Histogram.build()
.name("processing_duration_seconds")
.help("Processing duration")
.linearBuckets(0.01, 0.01, 5)
.register();
// Exponential buckets: 1, 2, 4, 8, 16, 32 seconds
Histogram batchSize = Histogram.build()
.name("batch_processing_seconds")
.help("Batch processing time")
.exponentialBuckets(1, 2, 6)
.register();Record values in histogram buckets with optional exemplar support.
/**
* Record an observation in the histogram
* @param amt Value to observe (typically >= 0)
*/
public void observe(double amt);
/**
* Record observation with exemplar for trace correlation
* @param amt Value to observe
* @param exemplarLabels Trace labels as name/value pairs
*/
public void observeWithExemplar(double amt, String... exemplarLabels);
/**
* Record observation with exemplar using Map for labels
* @param amt Value to observe
* @param exemplarLabels Map of label names to values
*/
public void observeWithExemplar(double amt, Map<String, String> exemplarLabels);Usage Examples:
// Basic observations
requestDuration.observe(0.123); // 123ms request
responseSizes.observe(1024.0); // 1KB response
// With exemplars for tracing
requestDuration.observeWithExemplar(0.456, "trace_id", "abc123");
Map<String, String> traceInfo = Map.of(
"trace_id", "xyz789",
"span_id", "span123"
);
requestDuration.observeWithExemplar(0.789, traceInfo);Use histograms for automatic duration measurement and timing operations.
/**
* Start a timer for duration measurement
* @return Timer instance for duration tracking
*/
public Timer startTimer();
/**
* Time a Runnable execution and observe duration
* @param timeable Code to time
* @return Duration in seconds
*/
public double time(Runnable timeable);
/**
* Time a Callable execution and observe duration
* @param timeable Code to time
* @return Result from callable
* @throws RuntimeException if callable throws exception
*/
public <E> E time(Callable<E> timeable);
/**
* Time execution with exemplar support
* @param timeable Code to time
* @param exemplarLabels Trace labels for exemplar
* @return Duration in seconds
*/
public double timeWithExemplar(Runnable timeable, String... exemplarLabels);
/**
* Time callable with exemplar support
* @param timeable Code to time
* @param exemplarLabels Trace labels for exemplar
* @return Result from callable
*/
public <E> E timeWithExemplar(Callable<E> timeable, String... exemplarLabels);Timer provides duration measurement and exemplar support for histogram metrics.
public static class Timer implements Closeable {
/**
* Observe elapsed duration since timer start
* @return Elapsed duration in seconds
*/
public double observeDuration();
/**
* Observe duration with exemplar support
* @param exemplarLabels Trace labels for exemplar
* @return Elapsed duration in seconds
*/
public double observeDurationWithExemplar(String... exemplarLabels);
/**
* Observe duration with exemplar Map
* @param exemplarLabels Map of trace labels
* @return Elapsed duration in seconds
*/
public double observeDurationWithExemplar(Map<String, String> exemplarLabels);
/**
* Equivalent to observeDuration() - implements Closeable
*/
public void close();
}Usage Examples:
// Manual timer usage
Histogram.Timer timer = requestDuration.startTimer();
try {
processRequest();
} finally {
timer.observeDuration();
}
// Try-with-resources timer
try (Histogram.Timer timer = requestDuration.startTimer()) {
processRequest(); // Automatically observes duration
}
// Lambda timing
double duration = requestDuration.time(() -> {
processRequest();
});
// Timing with return value
String response = requestDuration.time(() -> {
return generateResponse();
});
// Timer with exemplars
timer.observeDurationWithExemplar("trace_id", "abc123");Work with multi-dimensional histograms using label values.
/**
* Get histogram child for specific label values
* @param labelValues Values for each label name (must match count)
* @return Histogram.Child instance for the label combination
* @throws IllegalArgumentException if wrong number of labels
*/
public Histogram.Child labels(String... labelValues);
/**
* Remove histogram child for specific label values
* @param labelValues Values identifying the child to remove
*/
public void remove(String... labelValues);
/**
* Remove all histogram children
*/
public void clear();Histogram.Child provides the same observation and timing operations for labeled instances.
public static class Child {
/** Record observation in child histogram */
public void observe(double amt);
/** Record observation with exemplar */
public void observeWithExemplar(double amt, String... exemplarLabels);
public void observeWithExemplar(double amt, Map<String, String> exemplarLabels);
/** Start timer for child histogram */
public Timer startTimer();
/** Time operations for child histogram */
public double time(Runnable timeable);
public <E> E time(Callable<E> timeable);
public double timeWithExemplar(Runnable timeable, String... exemplarLabels);
public <E> E timeWithExemplar(Callable<E> timeable, String... exemplarLabels);
/** Get histogram data snapshot */
public Value get();
}Access histogram bucket counts, sum, and exemplar data.
public static class Value {
/** Sum of all observed values */
public final double sum;
/** Cumulative counts for each bucket */
public final double[] buckets;
/** Exemplars for each bucket (may contain nulls) */
public final Exemplar[] exemplars;
/** Creation timestamp in milliseconds */
public final long created;
}Usage Example:
// HTTP request monitoring
Histogram httpDuration = Histogram.build()
.name("http_request_duration_seconds")
.help("HTTP request duration")
.labelNames("method", "status")
.buckets(0.001, 0.01, 0.1, 1.0, 10.0)
.register();
// Track requests by method and status
Histogram.Child getSuccess = httpDuration.labels("GET", "200");
Histogram.Child postError = httpDuration.labels("POST", "500");
// Time requests
getSuccess.time(() -> handleGetRequest());
postError.observe(2.5); // 2.5 second failed request
// Access histogram data
Histogram.Child.Value data = getSuccess.get();
System.out.println("Total requests: " + data.buckets[data.buckets.length - 1]);
System.out.println("Total duration: " + data.sum + " seconds");Histogram uses default buckets optimized for web/RPC latencies:
.005, .01, .025, .05, .075, .1, .25, .5, .75, 1, 2.5, 5, 7.5, 10 (seconds)// API latency monitoring
Histogram apiLatency = Histogram.build()
.name("api_request_duration_seconds")
.help("API request latency")
.labelNames("endpoint", "method")
.buckets(0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0)
.register();
// File size distribution
Histogram fileSize = Histogram.build()
.name("file_size_bytes")
.help("File size distribution")
.exponentialBuckets(1024, 2, 10) // 1KB to 512KB
.register();
// Queue processing time
Histogram queueProcessing = Histogram.build()
.name("queue_processing_seconds")
.help("Queue item processing time")
.linearBuckets(0.1, 0.1, 10) // 0.1s to 1.0s
.register();Install with Tessl CLI
npx tessl i tessl/maven-io-prometheus--simpleclient