1. import java.util.*;
  2. import java.util.concurrent.*;
  3. import java.time.Instant;
  4. class TimestampMonitor {
  5. private final int maxRequestsPerWindow;
  6. private final long windowDurationMillis;
  7. private final Map<String, List<Instant>> requestTimestamps; // Key: identifier, Value: List of timestamps
  8. private final Map<String, BlockingQueue<Instant>> requestQueue; // Queue of requests for each identifier
  9. private final ExecutorService rateLimiter;
  10. public TimestampMonitor(int maxRequestsPerWindow, long windowDurationMillis) {
  11. this.maxRequestsPerWindow = maxRequestsPerWindow;
  12. this.windowDurationMillis = windowDurationMillis;
  13. this.requestTimestamps = new HashMap<>();
  14. this.requestQueue = new HashMap<>();
  15. this.rateLimiter = Executors.newFixedThreadPool(10); //Adjust thread pool size as needed
  16. }
  17. public synchronized boolean allowRequest(String identifier) {
  18. // Get the current time
  19. Instant now = Instant.now();
  20. // Get timestamps for the identifier
  21. List<Instant> timestamps = requestTimestamps.getOrDefault(identifier, new ArrayList<>());
  22. // Remove timestamps older than the window duration
  23. timestamps.removeIf(ts -> now.minusMillis(windowDurationMillis).isBefore(ts));
  24. // Check if the number of requests within the window exceeds the limit
  25. if (timestamps.size() >= maxRequestsPerWindow) {
  26. return false; // Rate limit exceeded
  27. }
  28. // Add the current timestamp to the list
  29. timestamps.add(now);
  30. requestTimestamps.put(identifier, timestamps);
  31. // Add the timestamp to the queue
  32. requestQueue.computeIfAbsent(identifier, k -> new LinkedBlockingQueue<>()).offer(now);
  33. return true; // Request allowed
  34. }
  35. public void processQueue(String identifier) {
  36. //Process requests from the queue for a given identifier
  37. BlockingQueue<Instant> queue = requestQueue.get(identifier);
  38. while (!queue.isEmpty()) {
  39. Instant timestamp = queue.poll();
  40. //Simulate processing the request with the timestamp
  41. System.out.println("Processing request from " + identifier + " at: " + timestamp);
  42. rateLimiter.submit(() -> {
  43. try {
  44. Thread.sleep(100); // Simulate processing time
  45. } catch (InterruptedException e) {
  46. Thread.currentThread().interrupt();
  47. }
  48. });
  49. }
  50. }
  51. public void shutdown() {
  52. rateLimiter.shutdown();
  53. try {
  54. rateLimiter.awaitTermination(5, TimeUnit.SECONDS);
  55. } catch (InterruptedException e) {
  56. Thread.currentThread().interrupt();
  57. }
  58. }
  59. }

Add your comment