import java.util.concurrent.ConcurrentLinkedQueue;
public class RequestThrottle {
private final int maxRequestsPerSecond;
private final ConcurrentLinkedQueue<Long> requestTimestamps;
public RequestThrottle(int maxRequestsPerSecond) {
this.maxRequestsPerSecond = maxRequestsPerSecond;
this.requestTimestamps = new ConcurrentLinkedQueue<>();
}
public boolean allowRequest() {
long now = System.currentTimeMillis();
// Remove timestamps older than 1 second
while (!requestTimestamps.isEmpty() && requestTimestamps.peek() <= now - 1000) {
requestTimestamps.poll();
}
// Check if the request limit has been exceeded
if (requestTimestamps.size() >= maxRequestsPerSecond) {
return false; // Throttled
}
requestTimestamps.offer(now); // Add the current timestamp
return true; // Allowed
}
public static void main(String[] args) throws InterruptedException {
// Example usage:
RequestThrottle throttle = new RequestThrottle(5); // Allow 5 requests per second
for (int i = 0; i < 10; i++) {
if (throttle.allowRequest()) {
System.out.println("Request " + (i + 1) + " allowed.");
} else {
System.out.println("Request " + (i + 1) + " throttled.");
}
Thread.sleep(100); // Simulate requests coming in
}
}
}
Add your comment