1. import java.util.concurrent.ConcurrentHashMap;
  2. import java.util.concurrent.atomic.AtomicInteger;
  3. public class RequestThrottler {
  4. private final ConcurrentHashMap<String, AtomicInteger> requestCounts = new ConcurrentHashMap<>(); // Entry ID to request count
  5. private final long throttleWindowMillis; // Time window for throttling
  6. private final long maxRequestsPerWindow; // Maximum requests allowed in the window
  7. public RequestThrottler(long throttleWindowMillis, long maxRequestsPerWindow) {
  8. this.throttleWindowMillis = throttleWindowMillis;
  9. this.maxRequestsPerWindow = maxRequestsPerWindow;
  10. }
  11. public boolean allowRequest(String entryId) {
  12. // Get the current count for the entry ID
  13. AtomicInteger count = requestCounts.computeIfAbsent(entryId, k -> new AtomicInteger(0));
  14. long now = System.currentTimeMillis();
  15. // Reset count if outside the throttle window
  16. if (now - count.getAndSet(0, 0) > throttleWindowMillis) {
  17. count.set(0, 0); // Reset count
  18. }
  19. // Check if the request is within the limit
  20. if (count.get() < maxRequestsPerWindow) {
  21. count.incrementAndGet(); // Increment the request count
  22. return true;
  23. } else {
  24. return false; // Throttle - request denied
  25. }
  26. }
  27. public void removeEntry(String entryId) {
  28. requestCounts.remove(entryId);
  29. }
  30. public static void main(String[] args) throws InterruptedException {
  31. RequestThrottler throttler = new RequestThrottler(1000, 5); // Throttle to 5 requests per second
  32. for (int i = 0; i < 10; i++) {
  33. if (throttler.allowRequest("entry1")) {
  34. System.out.println("Request allowed for entry1");
  35. } else {
  36. System.out.println("Request throttled for entry1");
  37. }
  38. Thread.sleep(100); // Simulate request delay
  39. }
  40. throttler.removeEntry("entry1");
  41. for (int i = 0; i < 5; i++) {
  42. if (throttler.allowRequest("entry1")) {
  43. System.out.println("Request allowed for entry1");
  44. } else {
  45. System.out.println("Request throttled for entry1");
  46. }
  47. Thread.sleep(200); // Simulate request delay
  48. }
  49. }
  50. }

Add your comment