import java.time.LocalTime;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class TimeWatcher {
private final ConcurrentHashMap<LocalTime, Integer> timeCounts = new ConcurrentHashMap<>(); // Store time and change count
private final int rateLimit = 5; // Max changes allowed per second
private final long interval = 1000; // Check interval in milliseconds (1 second)
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
public void watchTimeChanges() {
scheduler.scheduleAtFixedRate(this::checkTimeChanges, 0, interval, TimeUnit.MILLISECONDS);
}
private void checkTimeChanges() {
LocalTime currentTime = LocalTime.now();
// Increment count for the current time
timeCounts.computeIfAbsent(currentTime, k -> 1).incrementAndGet();
// Rate limiting logic
if (timeCounts.get(currentTime) > rateLimit) {
// Handle rate limit exceeded (e.g., log, throttle)
System.out.println("Rate limit exceeded for time: " + currentTime);
// Reset the count for this time to avoid continuous exceeding
timeCounts.remove(currentTime);
}
}
public static void main(String[] args) {
TimeWatcher watcher = new TimeWatcher();
watcher.watchTimeChanges();
// Keep the main thread alive to allow the scheduler to run.
try {
Thread.sleep(60000); // Run for 60 seconds
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
watcher.scheduler.shutdown();
}
}
}
Add your comment