Class LockFreeFixedSizeSlidingWindowMetrics

java.lang.Object
io.github.resilience4j.core.metrics.LockFreeFixedSizeSlidingWindowMetrics
All Implemented Interfaces:
Metrics

public class LockFreeFixedSizeSlidingWindowMetrics extends Object implements Metrics
Implements a lock-free sliding window using a single linked list, represented by a head and a tail reference.

The idea is to initialize the list to the window size, where node N represents the stats for the N-th entry. Besides the stats for the N-th entry, it also contains the stats for the whole window, which are carried over on each new added entry.

When a new record is added, the size of the window is maintained:

  1. A new node is added at the tail of the list.
  2. The head of the list is moved to the next node.
  3. The tail of the list is moved to the next node.

As these operations need to happen atomically, we use the VarHandle API to perform CAS operations on the head, tail and next references. However, these updates are not atomically happening across these references, so we can end up that each reference is updated by a different thread.

The algorithm is based on the following conditions:

  • if there is no next node -> try to add one
  • else, if the head and tail represent the same N-th stats -> advance the head
  • else -> advance the tail

All these operations are done via compare-and-swap operations.

  • Constructor Details

    • LockFreeFixedSizeSlidingWindowMetrics

      public LockFreeFixedSizeSlidingWindowMetrics(int windowSize)
  • Method Details

    • record

      public Snapshot record(long duration, TimeUnit durationUnit, Metrics.Outcome outcome)
      Description copied from interface: Metrics
      Records a call.
      Specified by:
      record in interface Metrics
      Parameters:
      duration - the duration of the call
      durationUnit - the time unit of the duration
      outcome - the outcome of the call
    • getSnapshot

      public Snapshot getSnapshot()
      Description copied from interface: Metrics
      Returns a snapshot.
      Specified by:
      getSnapshot in interface Metrics
      Returns:
      a snapshot