import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
public class TimestampThrottler {
private final int maxRequestsPerSecond;
private final ConcurrentLinkedQueue<Long> requestQueue = new ConcurrentLinkedQueue<>();
private final AtomicInteger requestCount = new AtomicInteger(0);
public TimestampThrottler(int maxRequestsPerSecond) {
this.maxRequestsPerSecond = maxRequestsPerSecond;
}
public boolean allowRequest(long timestamp) {
// Calculate the number of requests allowed in the current second.
int requestsThisSecond = requestCount.get();
// If we've exceeded the limit, return false.
if (requestsThisSecond >= maxRequestsPerSecond) {
return false;
}
// Add the timestamp to the queue.
requestQueue.offer(timestamp);
requestCount.incrementAndGet();
return true;
}
}
Add your comment