Class TokenBucket

java.lang.Object
org.drasyl.util.TokenBucket

public class TokenBucket extends Object
This class implements the token bucket algorithm as a leaky bucket. This means that the bucket has a finite capacity and added tokens that exceed this capacity are lost. The bucket is filled with new tokens at a constant time rate.

This algorithm allows rate-limiting operations (e.g. number of messages sent per time unit). The bucket capacity can be used to control whether capacities unused in the past may be used up later, or whether they "overflow" from the bucket and are lost unused.

This implementation has been inspired by: token-bucket

  • Constructor Details

    • TokenBucket

      public TokenBucket(long capacity, Duration refillInterval, boolean doBusyWait)
      Creates a new leaky token bucket.
      Parameters:
      capacity - overall capacity of the token bucket
      refillInterval - refill token at a fixed interval
      doBusyWait - specifies if busy waiting should be used when calling consume() or not. busy waiting allows a more efficient consumption of tokens, but blocks a thread permanently. should only be used with refill intervals of less than 20 milliseconds.
      Throws:
      IllegalArgumentException - if capacity or refillInterval contain non-positive values
  • Method Details

    • consume

      public void consume()
      Consumes a token from the bucket. If the bucket does not currently contain a token, this method blocks until a token becomes available.
    • availableTokens

      public long availableTokens()
      Returns the number of available tokens in the bucket.
      Returns:
      numebr of available tokens in the bucket