Class TokenBucket


  • public class TokenBucket
    extends java.lang.Object
    See Also:
    Token Bucket on Wikipedia This implementation aims to be very high performance with the goal of supporting a very large number of TokenBuckets in an application; thus avoiding an auxilliary thread to refill the bucket.
    • Constructor Summary

      Constructors 
      Constructor Description
      TokenBucket​(long capacity, long refillAmount, long refillInterval, java.util.concurrent.TimeUnit refillUnit)  
      TokenBucket​(long capacity, long refillAmount, long refillInterval, java.util.concurrent.TimeUnit refillUnit, java.time.Clock clock)
      This constructor should only be used by tests.
    • Constructor Detail

      • TokenBucket

        public TokenBucket​(long capacity,
                           long refillAmount,
                           long refillInterval,
                           java.util.concurrent.TimeUnit refillUnit,
                           java.time.Clock clock)
        This constructor should only be used by tests. Application should not specify it's own instance of Clock
        Parameters:
        capacity -
        refillAmount -
        refillInterval -
        refillUnit -
        clock -
      • TokenBucket

        public TokenBucket​(long capacity,
                           long refillAmount,
                           long refillInterval,
                           java.util.concurrent.TimeUnit refillUnit)
        Parameters:
        capacity - The maximum number of tokens that the bucket can have at any one time. Any refill beyond the capacity is lost. A capacity larger than the refillAmount supports bursting.
        refillAmount - The number of tokens added to the bucket each interval
        refillInterval - The interval of time between refills of the bucket
        refillUnit - The TimeUnit for the refillInterval
    • Method Detail

      • getStaleTokenCount

        public long getStaleTokenCount()
        This method does not call #update(), so it is only accurate as of the last time #tryConsume() was called
        Returns:
        number of tokens remaining in the bucket
      • tryConsume

        public boolean tryConsume​(long tokensToConsume)
      • tryConsume

        public boolean tryConsume()
      • getAmortizedRefillPerSecond

        public float getAmortizedRefillPerSecond()
      • getStaleUsageRatio

        public double getStaleUsageRatio()