1. import java.util.concurrent.ConcurrentLinkedQueue;
  2. import java.util.concurrent.atomic.AtomicInteger;
  3. public class RequestThrottler {
  4. private final int maxRequestsPerSecond; // Maximum requests allowed per second
  5. private final ConcurrentLinkedQueue<Long> requestTimestamps; //Queue to store request timestamps
  6. private final AtomicInteger requestCount; //Atomic counter for request count
  7. public RequestThrottler(int maxRequestsPerSecond) {
  8. this.maxRequestsPerSecond = maxRequestsPerSecond;
  9. this.requestTimestamps = new ConcurrentLinkedQueue<>();
  10. this.requestCount = new AtomicInteger(0);
  11. }
  12. /**
  13. * Processes a request, throttling it if necessary.
  14. *
  15. * @param timestamp The timestamp of the request.
  16. * @return True if the request is allowed, false otherwise.
  17. */
  18. public boolean allowRequest(long timestamp) {
  19. // Remove outdated timestamps from the queue
  20. while (!requestTimestamps.isEmpty() && requestTimestamps.peek() <= timestamp - 1000) { //remove timestamps older than 1 second.
  21. requestTimestamps.poll();
  22. }
  23. // Check if the request count exceeds the limit
  24. if (requestCount.get() >= maxRequestsPerSecond) {
  25. return false; // Request throttled
  26. }
  27. // Allow the request and update the count and timestamp
  28. requestCount.incrementAndGet();
  29. requestTimestamps.offer(timestamp);
  30. return true; // Request allowed
  31. }
  32. public static void main(String[] args) {
  33. //Example Usage
  34. RequestThrottler throttler = new RequestThrottler(5); // Allow 5 requests per second
  35. for (int i = 0; i < 10; i++) {
  36. long timestamp = System.currentTimeMillis();
  37. if (throttler.allowRequest(timestamp)) {
  38. System.out.println("Request allowed at: " + timestamp);
  39. } else {
  40. System.out.println("Request throttled at: " + timestamp);
  41. }
  42. try {
  43. Thread.sleep(100); // Simulate requests arriving at different times
  44. } catch (InterruptedException e) {
  45. e.printStackTrace();
  46. }
  47. }
  48. }
  49. }

Add your comment