Class SlidingWindow<T>

java.lang.Object
io.prometheus.metrics.core.metrics.SlidingWindow<T>

public class SlidingWindow<T> extends Object
Maintains a ring buffer of T to implement a sliding time window.

This is used to maintain a sliding window of CKMSQuantiles for Summary metrics.

It is implemented in a generic way so that 3rd party libraries can use it for implementing sliding windows.

Thread Safety: This class uses coarse-grained synchronized methods for simplicity and correctness. All public methods (current() and observe(double)) are synchronized, which ensures thread-safe access to the ring buffer and rotation logic.

Performance Note: The synchronized approach may cause contention under high-frequency observations.

However, given that Summary metrics are less commonly used (Histogram is generally preferred), and the observation frequency is typically lower than Counter increments, the current implementation provides an acceptable trade-off between simplicity and performance.

  • Field Details

    • constructor

      private final Supplier<T> constructor
    • observeFunction

      private final ObjDoubleConsumer<T> observeFunction
    • ringBuffer

      private final T[] ringBuffer
    • currentBucket

      private int currentBucket
    • lastRotateTimestampMillis

      private long lastRotateTimestampMillis
    • durationBetweenRotatesMillis

      private final long durationBetweenRotatesMillis
    • currentTimeMillis

      private final LongSupplier currentTimeMillis
  • Constructor Details

    • SlidingWindow

      public SlidingWindow(Class<T> clazz, Supplier<T> constructor, ObjDoubleConsumer<T> observeFunction, long maxAgeSeconds, int ageBuckets)
      Example: If the maxAgeSeconds is 60 and ageBuckets is 3, then 3 instances of T are maintained and the sliding window moves to the next instance of T every 20 seconds.
      Parameters:
      clazz - type of T
      constructor - for creating a new instance of T as the old one gets evicted
      observeFunction - for observing a value (e.g. calling t.observe(value)
      maxAgeSeconds - after this amount of time an instance of T gets evicted.
      ageBuckets - number of age buckets.
    • SlidingWindow

      SlidingWindow(Class<T> clazz, Supplier<T> constructor, ObjDoubleConsumer<T> observeFunction, long maxAgeSeconds, int ageBuckets, LongSupplier currentTimeMillis)
  • Method Details

    • current

      public T current()
      Get the currently active instance of T.
    • observe

      public void observe(double value)
      Observe a value.
    • rotate

      private T rotate()