1. import java.time.LocalTime;
  2. import java.util.concurrent.ConcurrentHashMap;
  3. import java.util.concurrent.Executors;
  4. import java.util.concurrent.ScheduledExecutorService;
  5. import java.util.concurrent.TimeUnit;
  6. public class TimeWatcher {
  7. private final ConcurrentHashMap<LocalTime, Integer> timeCounts = new ConcurrentHashMap<>(); // Store time and change count
  8. private final int rateLimit = 5; // Max changes allowed per second
  9. private final long interval = 1000; // Check interval in milliseconds (1 second)
  10. private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
  11. public void watchTimeChanges() {
  12. scheduler.scheduleAtFixedRate(this::checkTimeChanges, 0, interval, TimeUnit.MILLISECONDS);
  13. }
  14. private void checkTimeChanges() {
  15. LocalTime currentTime = LocalTime.now();
  16. // Increment count for the current time
  17. timeCounts.computeIfAbsent(currentTime, k -> 1).incrementAndGet();
  18. // Rate limiting logic
  19. if (timeCounts.get(currentTime) > rateLimit) {
  20. // Handle rate limit exceeded (e.g., log, throttle)
  21. System.out.println("Rate limit exceeded for time: " + currentTime);
  22. // Reset the count for this time to avoid continuous exceeding
  23. timeCounts.remove(currentTime);
  24. }
  25. }
  26. public static void main(String[] args) {
  27. TimeWatcher watcher = new TimeWatcher();
  28. watcher.watchTimeChanges();
  29. // Keep the main thread alive to allow the scheduler to run.
  30. try {
  31. Thread.sleep(60000); // Run for 60 seconds
  32. } catch (InterruptedException e) {
  33. e.printStackTrace();
  34. } finally {
  35. watcher.scheduler.shutdown();
  36. }
  37. }
  38. }

Add your comment