package com.malagasys.slidingwindow; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class SlidingWindowMap { private final Map map = new HashMap<>(); public SlidingWindowMap(Set keys, int maxCount, long periodMs) { //Just create a sliding window per key. for (String key : keys) { map.put(key, new SlidingWindow(periodMs, maxCount)); } } public String getNextKey() { String nextKey = null; long currentTime = System.currentTimeMillis(); for (Map.Entry e : map.entrySet()) { //Slide the window to match current timestamp e.getValue().slideTo(currentTime); //If the window is not full yet, accept the key as the next key if (!e.getValue().isFull()) { e.getValue().logcall(currentTime); nextKey = e.getKey(); break; } } return nextKey; } //========= Run ============ public static void main(String[] args) throws Exception { Set keys = new HashSet<>(Arrays.asList("key_a", "key_b", "key_c", "key_d")); SlidingWindowMap map = new SlidingWindowMap(keys, 5, 30000); for (int i = 0; i < 40; i++) { System.out.println(map.getNextKey()); if (i%3 == 0) { Thread.sleep(5000); } } } }