1. import java.util.concurrent.ConcurrentLinkedQueue;
  2. public class RequestThrottle {
  3. private final int maxRequestsPerSecond;
  4. private final ConcurrentLinkedQueue<Long> requestTimestamps;
  5. public RequestThrottle(int maxRequestsPerSecond) {
  6. this.maxRequestsPerSecond = maxRequestsPerSecond;
  7. this.requestTimestamps = new ConcurrentLinkedQueue<>();
  8. }
  9. public boolean allowRequest() {
  10. long now = System.currentTimeMillis();
  11. // Remove timestamps older than 1 second
  12. while (!requestTimestamps.isEmpty() && requestTimestamps.peek() <= now - 1000) {
  13. requestTimestamps.poll();
  14. }
  15. // Check if the request limit has been exceeded
  16. if (requestTimestamps.size() >= maxRequestsPerSecond) {
  17. return false; // Throttled
  18. }
  19. requestTimestamps.offer(now); // Add the current timestamp
  20. return true; // Allowed
  21. }
  22. public static void main(String[] args) throws InterruptedException {
  23. // Example usage:
  24. RequestThrottle throttle = new RequestThrottle(5); // Allow 5 requests per second
  25. for (int i = 0; i < 10; i++) {
  26. if (throttle.allowRequest()) {
  27. System.out.println("Request " + (i + 1) + " allowed.");
  28. } else {
  29. System.out.println("Request " + (i + 1) + " throttled.");
  30. }
  31. Thread.sleep(100); // Simulate requests coming in
  32. }
  33. }
  34. }

Add your comment