import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
public class RequestThrottler {
private final ConcurrentHashMap<String, AtomicInteger> requestCounts = new ConcurrentHashMap<>(); // Entry ID to request count
private final long throttleWindowMillis; // Time window for throttling
private final long maxRequestsPerWindow; // Maximum requests allowed in the window
public RequestThrottler(long throttleWindowMillis, long maxRequestsPerWindow) {
this.throttleWindowMillis = throttleWindowMillis;
this.maxRequestsPerWindow = maxRequestsPerWindow;
}
public boolean allowRequest(String entryId) {
// Get the current count for the entry ID
AtomicInteger count = requestCounts.computeIfAbsent(entryId, k -> new AtomicInteger(0));
long now = System.currentTimeMillis();
// Reset count if outside the throttle window
if (now - count.getAndSet(0, 0) > throttleWindowMillis) {
count.set(0, 0); // Reset count
}
// Check if the request is within the limit
if (count.get() < maxRequestsPerWindow) {
count.incrementAndGet(); // Increment the request count
return true;
} else {
return false; // Throttle - request denied
}
}
public void removeEntry(String entryId) {
requestCounts.remove(entryId);
}
public static void main(String[] args) throws InterruptedException {
RequestThrottler throttler = new RequestThrottler(1000, 5); // Throttle to 5 requests per second
for (int i = 0; i < 10; i++) {
if (throttler.allowRequest("entry1")) {
System.out.println("Request allowed for entry1");
} else {
System.out.println("Request throttled for entry1");
}
Thread.sleep(100); // Simulate request delay
}
throttler.removeEntry("entry1");
for (int i = 0; i < 5; i++) {
if (throttler.allowRequest("entry1")) {
System.out.println("Request allowed for entry1");
} else {
System.out.println("Request throttled for entry1");
}
Thread.sleep(200); // Simulate request delay
}
}
}
Add your comment