Package org.drasyl.util
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 Summary
Constructors Constructor Description TokenBucket(long capacity, Duration refillInterval, boolean doBusyWait)
Creates a new leaky token bucket.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description long
availableTokens()
Returns the number of available tokens in the bucket.void
consume()
Consumes a token from the bucket.
-
-
-
Constructor Detail
-
TokenBucket
public TokenBucket(long capacity, Duration refillInterval, boolean doBusyWait)
Creates a new leaky token bucket.- Parameters:
capacity
- overall capacity of the token bucketrefillInterval
- refill token at a fixed intervaldoBusyWait
- specifies if busy waiting should be used when callingconsume()
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
- ifcapacity
orrefillInterval
contain non-positive values
-
-
Method Detail
-
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
-
-