Class ProbabilitySampler

  • All Implemented Interfaces:
    Sampler

    public class ProbabilitySampler
    extends java.lang.Object
    implements Sampler
    This implementation of Sampler samples based on a sampling probability (or sampling rate) between 0.0 and 1.0.

    A sampling rate of 0.5 means that 50% of all transactions should be sampled.

    Implementation notes:

    We are taking advantage of the fact, that the Id is randomly generated. So instead of generating another random number, we just see if the long value returned by Id.getLeastSignificantBits() falls into the range between the lowerBound and the higherBound. This is a visual representation of the mechanism with a sampling rate of 0.5 (=50%):
     Long.MIN_VALUE        0                     Long.MAX_VALUE
     v                     v                     v
     [----------[----------|----------]----------]
                ^                     ^
                lowerBound            higherBound = Long.MAX_VALUE * samplingRate
                = Long.MAX_VALUE * samplingRate * -1
     
    • Method Detail

      • of

        public static Sampler of​(double samplingRate)
      • isSampled

        public boolean isSampled​(Id traceId)
        Description copied from interface: Sampler
        Determines whether the given transaction should be sampled.
        Specified by:
        isSampled in interface Sampler
        Parameters:
        traceId - The id of the transaction.
        Returns:
        The sampling decision.
      • getSampleRate

        public double getSampleRate()
        Specified by:
        getSampleRate in interface Sampler
        Returns:
        current sample rate
      • getTraceStateHeader

        public java.lang.String getTraceStateHeader()
        Specified by:
        getTraceStateHeader in interface Sampler
        Returns:
        sample rate as (constant) header for context propagation

        While the tracestate header is not related to sampler itself, putting this here allows to reuse the same String instance as long as the sample rate does not change to minimize allocation