Skip to content

Instantly share code, notes, and snippets.

@lobster1234
Last active October 30, 2022 02:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lobster1234/88422d72472b14f25e1b7373cfeea58c to your computer and use it in GitHub Desktop.
Save lobster1234/88422d72472b14f25e1b7373cfeea58c to your computer and use it in GitHub Desktop.
Token Bucket Rate Limiter Implementation
package org.lobster1234.misc;
import java.util.concurrent.*;
import java.util.function.Consumer;
/**
* Implementation of a token bucket rate limiter.
*/
public class TokenBucketRateLimiter {
//Need to figure out if any other data structure is better here
//Stack<Integer> tokens = new Stack<>();
int tokens;
/**
*
* @param numTokens The number of tokens allowed
* @param time The timeframe for the above
*/
public TokenBucketRateLimiter(int numTokens, TimeUnit time){
//lets create our bucket and initialize it
tokens = numTokens;
//lets create a thread that will keep filling the bucket, which we can just use an array for
Runnable bucketFiller = ()-> tokens = numTokens;
//now we schedule this runnable to execute every TimeUnit
ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
service.scheduleAtFixedRate(bucketFiller,0,1,time);
}
/**
*
* @param request The payload
* @param success The function to call with success
* @param failure The function to call for failure (throttle)
*/
public void execute(RequestPayLoad request, Consumer<RequestPayLoad> success, Consumer<RequestPayLoad> failure){
if(tokens<=0){
System.out.println("Throttled, no tokens in the bucket");
failure.accept(request);
}else{
--tokens;
System.out.println("Removing token, new size is " + tokens);
success.accept(request);
}
}
}
class RequestPayLoad{
String payload;
public RequestPayLoad(String string){
this.payload = string;
}
public String getPayload(){
return payload;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment