1. import java.util.concurrent.ConcurrentLinkedQueue;
  2. import java.util.concurrent.atomic.AtomicInteger;
  3. public class TimestampThrottler {
  4. private final int maxRequestsPerSecond;
  5. private final ConcurrentLinkedQueue<Long> requestQueue = new ConcurrentLinkedQueue<>();
  6. private final AtomicInteger requestCount = new AtomicInteger(0);
  7. public TimestampThrottler(int maxRequestsPerSecond) {
  8. this.maxRequestsPerSecond = maxRequestsPerSecond;
  9. }
  10. public boolean allowRequest(long timestamp) {
  11. // Calculate the number of requests allowed in the current second.
  12. int requestsThisSecond = requestCount.get();
  13. // If we've exceeded the limit, return false.
  14. if (requestsThisSecond >= maxRequestsPerSecond) {
  15. return false;
  16. }
  17. // Add the timestamp to the queue.
  18. requestQueue.offer(timestamp);
  19. requestCount.incrementAndGet();
  20. return true;
  21. }
  22. }

Add your comment