Class TimeBucketCounter


  • public class TimeBucketCounter
    extends TimeBucketCounterBase
    A fast counter that optimizes efficiency at the expense of approximate bucket indexing.
    • Constructor Summary

      Constructors 
      Constructor Description
      TimeBucketCounter​(int bucketDuration, java.util.concurrent.ScheduledExecutorService executorService)  
    • Constructor Detail

      • TimeBucketCounter

        public TimeBucketCounter​(int bucketDuration,
                                 java.util.concurrent.ScheduledExecutorService executorService)
    • Method Detail

      • getBucketIndex

        public long getBucketIndex​(long timestamp)
        Calculate the bucket index for the specific timestamp.

        Calculates the current time bucket index by shifting bits for fast division, e.g. shift 16 bits is the same as dividing by 65,536 which is about 1:05m.

        Specified by:
        getBucketIndex in class TimeBucketCounterBase
        Parameters:
        timestamp - the specific timestamp in milliseconds
        Returns:
        prefix the bucket key prefix for the specific timestamp
      • getNumBits

        public int getNumBits()
      • getActualDuration

        public int getActualDuration()
        The actual duration may differ from the configured duration because it is set to the next power of 2 value in order to perform very fast bit shift arithmetic.
        Returns:
        the actual bucket duration in milliseconds
      • determineShiftBitsOfDuration

        protected static int determineShiftBitsOfDuration​(int duration)
        Determines the bits of shift for the specific bucket duration in seconds, which used to figure out the correct bucket index.
        Parameters:
        duration - bucket duration in seconds
        Returns:
        bits to be shifted
      • getRatio

        public double getRatio()
        Returns the ratio between the configured duration param and the actual duration which will be set to the next power of 2. We then multiply the configured requests param by the same ratio in order to compensate for the added time, if any.
        Specified by:
        getRatio in class TimeBucketCounterBase
        Returns:
        the ratio, e.g. 1.092 if the actual duration is 65_536 for the configured duration of 60_000
      • getMillisUntilNextBucket

        public long getMillisUntilNextBucket()
        Description copied from class: TimeBucketCounterBase
        When we want to test a full bucket duration we need to sleep until the next bucket starts.

        WARNING: This method is used for test purpose.

        Specified by:
        getMillisUntilNextBucket in class TimeBucketCounterBase
        Returns:
        the number of milliseconds until the next bucket