import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
public class RequestThrottler {
private final int maxRequestsPerSecond; // Maximum requests allowed per second
private final ConcurrentLinkedQueue<Long> requestTimestamps; //Queue to store request timestamps
private final AtomicInteger requestCount; //Atomic counter for request count
public RequestThrottler(int maxRequestsPerSecond) {
this.maxRequestsPerSecond = maxRequestsPerSecond;
this.requestTimestamps = new ConcurrentLinkedQueue<>();
this.requestCount = new AtomicInteger(0);
}
/**
* Processes a request, throttling it if necessary.
*
* @param timestamp The timestamp of the request.
* @return True if the request is allowed, false otherwise.
*/
public boolean allowRequest(long timestamp) {
// Remove outdated timestamps from the queue
while (!requestTimestamps.isEmpty() && requestTimestamps.peek() <= timestamp - 1000) { //remove timestamps older than 1 second.
requestTimestamps.poll();
}
// Check if the request count exceeds the limit
if (requestCount.get() >= maxRequestsPerSecond) {
return false; // Request throttled
}
// Allow the request and update the count and timestamp
requestCount.incrementAndGet();
requestTimestamps.offer(timestamp);
return true; // Request allowed
}
public static void main(String[] args) {
//Example Usage
RequestThrottler throttler = new RequestThrottler(5); // Allow 5 requests per second
for (int i = 0; i < 10; i++) {
long timestamp = System.currentTimeMillis();
if (throttler.allowRequest(timestamp)) {
System.out.println("Request allowed at: " + timestamp);
} else {
System.out.println("Request throttled at: " + timestamp);
}
try {
Thread.sleep(100); // Simulate requests arriving at different times
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Add your comment