Token Bucket

By | August 27, 2021
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  
public class TokenBucket {

    private long maxBucketSize;
    private long refillRate; // per second
    private long currentBucketSize;
    private long lastRefillTimestamp;

    synchronized public boolean allowRequest(int token) {
        refill();
        if (currentBucketSize >= token) {
            currentBucketSize -= token;
            return true;
        }
        return false;
    }

    private void refill() {
        long now = System.nanoTime();
        double add = (now - lastRefillTimestamp) / 1e9 * refillRate;
        currentBucketSize = Math.min(currentBucketSize + (long)add, maxBucketSize);
        lastRefillTimestamp = now;
    }

}