import java.util.concurrent.ConcurrentLinkedQueue;
public class ApiThrottler {
private final int maxRequestsPerSecond; // Maximum requests allowed per second
private final ConcurrentLinkedQueue<Long> requestQueue = new ConcurrentLinkedQueue<>(); // Queue to store request timestamps
private final boolean dryRun; // Enable dry-run mode
public ApiThrottler(int maxRequestsPerSecond, boolean dryRun) {
this.maxRequestsPerSecond = maxRequestsPerSecond;
this.dryRun = dryRun;
}
public synchronized boolean allowRequest() {
long now = System.currentTimeMillis();
// Remove requests older than 1 second
while (!requestQueue.isEmpty() && requestQueue.peek() <= now - 1000) {
requestQueue.poll();
}
// Check if the rate limit is exceeded
if (requestQueue.size() >= maxRequestsPerSecond) {
if (dryRun) {
System.out.println("Dry Run: Request throttled. Rate limit exceeded.");
return false; // Simulate throttling in dry-run mode
} else {
try {
Thread.sleep(1000); // Wait for 1 second
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return false; // Actually throttle the request
}
}
requestQueue.offer(now); // Add the current request timestamp to the queue
return true; // Allow the request
}
public static void main(String[] args) throws InterruptedException {
// Example usage
int maxRequests = 5; // Allow 5 requests per second
boolean isDryRun = true; // Set to false for actual throttling
ApiThrottler throttler = new ApiThrottler(maxRequests, isDryRun);
for (int i = 0; i < 10; i++) {
if (throttler.allowRequest()) {
System.out.println("Request " + (i + 1) + " allowed.");
// Simulate API call here
} else {
System.out.println("Request " + (i + 1) + " throttled.");
}
Thread.sleep(200); // Simulate request interval
}
}
}
Add your comment