1. import java.util.concurrent.ConcurrentLinkedQueue;
  2. public class ApiThrottler {
  3. private final int maxRequestsPerSecond; // Maximum requests allowed per second
  4. private final ConcurrentLinkedQueue<Long> requestQueue = new ConcurrentLinkedQueue<>(); // Queue to store request timestamps
  5. private final boolean dryRun; // Enable dry-run mode
  6. public ApiThrottler(int maxRequestsPerSecond, boolean dryRun) {
  7. this.maxRequestsPerSecond = maxRequestsPerSecond;
  8. this.dryRun = dryRun;
  9. }
  10. public synchronized boolean allowRequest() {
  11. long now = System.currentTimeMillis();
  12. // Remove requests older than 1 second
  13. while (!requestQueue.isEmpty() && requestQueue.peek() <= now - 1000) {
  14. requestQueue.poll();
  15. }
  16. // Check if the rate limit is exceeded
  17. if (requestQueue.size() >= maxRequestsPerSecond) {
  18. if (dryRun) {
  19. System.out.println("Dry Run: Request throttled. Rate limit exceeded.");
  20. return false; // Simulate throttling in dry-run mode
  21. } else {
  22. try {
  23. Thread.sleep(1000); // Wait for 1 second
  24. } catch (InterruptedException e) {
  25. Thread.currentThread().interrupt();
  26. }
  27. return false; // Actually throttle the request
  28. }
  29. }
  30. requestQueue.offer(now); // Add the current request timestamp to the queue
  31. return true; // Allow the request
  32. }
  33. public static void main(String[] args) throws InterruptedException {
  34. // Example usage
  35. int maxRequests = 5; // Allow 5 requests per second
  36. boolean isDryRun = true; // Set to false for actual throttling
  37. ApiThrottler throttler = new ApiThrottler(maxRequests, isDryRun);
  38. for (int i = 0; i < 10; i++) {
  39. if (throttler.allowRequest()) {
  40. System.out.println("Request " + (i + 1) + " allowed.");
  41. // Simulate API call here
  42. } else {
  43. System.out.println("Request " + (i + 1) + " throttled.");
  44. }
  45. Thread.sleep(200); // Simulate request interval
  46. }
  47. }
  48. }

Add your comment