Rate limiter
unknown
java
a year ago
1.9 kB
8
Indexable
import java.util.LinkedList;
import java.util.Queue;
// RateLimiter Interface
public interface RateLimiter {
boolean acquire(); // Try to acquire a permit
}
// SlidingWindowRateLimiter Class
public class SlidingWindowRateLimiter implements RateLimiter {
private final int maxRequests; // Maximum number of requests allowed
private final long windowSize; // Size of the time window in milliseconds
private final Queue<Long> requestTimestamps; // Timestamps of requests
public SlidingWindowRateLimiter(int maxRequests, long windowSize) {
this.maxRequests = maxRequests;
this.windowSize = windowSize;
this.requestTimestamps = new LinkedList<>();
}
@Override
public synchronized boolean acquire() {
long now = System.currentTimeMillis();
// Remove timestamps outside the window
while (!requestTimestamps.isEmpty() && now - requestTimestamps.peek() > windowSize) {
requestTimestamps.poll();
}
if (requestTimestamps.size() < maxRequests) {
requestTimestamps.add(now);
return true;
} else {
return false;
}
}
}
// Main Application for Demonstration
public class RateLimiterDemo {
public static void main(String[] args) throws InterruptedException {
// Create a rate limiter with a maximum of 5 requests per 10 seconds
SlidingWindowRateLimiter rateLimiter = new SlidingWindowRateLimiter(5, 10000);
// Try to acquire permits
for (int i = 0; i < 10; i++) {
if (rateLimiter.acquire()) {
System.out.println("Request allowed: " + i);
} else {
System.out.println("Request denied: " + i);
}
Thread.sleep(1000); // Simulate some delay between requests
}
}
}
Editor is loading...
Leave a Comment