1. import java.util.HashMap;
  2. import java.util.Map;
  3. public class RateLimitedEntry {
  4. private final int maxRequests;
  5. private final long windowMs;
  6. private final Map<String, Integer> requestCounts;
  7. public RateLimitedEntry(int maxRequests, long windowMs) {
  8. this.maxRequests = maxRequests;
  9. this.windowMs = windowMs;
  10. this.requestCounts = new HashMap<>();
  11. }
  12. public synchronized boolean allowRequest(String identifier) {
  13. // Get the current time
  14. long currentTime = System.currentTimeMillis();
  15. // Reset counts if outside the window
  16. requestCounts.remove(identifier);
  17. requestCounts.put(identifier, 0);
  18. // Check if the identifier has exceeded the limit
  19. if (requestCounts.get(identifier) >= maxRequests) {
  20. return false; // Rate limit exceeded
  21. }
  22. // Increment the request count for this identifier
  23. requestCounts.put(identifier, requestCounts.get(identifier) + 1);
  24. return true; // Request allowed
  25. }
  26. public synchronized void resetCounts(String identifier) {
  27. requestCounts.remove(identifier);
  28. }
  29. public int getRemainingRequests(String identifier) {
  30. if(requestCounts.containsKey(identifier)) {
  31. return maxRequests - requestCounts.get(identifier);
  32. }
  33. return maxRequests;
  34. }
  35. }

Add your comment