package test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class SlidingWindowMap {
private int maxCount;
private long periodMs;
private Map<String, List<Long>> usedBufferMap = new HashMap<String, List<Long>>();
public SlidingWindowMap(Set<String> keys, int maxCount, long periodMs) {
Iterator<String> iterator = keys.iterator();
while(iterator.hasNext()){
String key = iterator.next();
usedBufferMap.put(key, new ArrayList<Long>());
}
this.maxCount = maxCount;
this.periodMs = periodMs;
}
/**
* @return a key that has been used less than `maxCount` times during the
* past `periodMs` milliseconds or null if no such key exists.
*/
public String getNextKey() {
for (Entry<String, List<Long>> entry: usedBufferMap.entrySet()){
cleanEntry(entry.getValue());
if (entry.getValue().size() < maxCount) {
entry.getValue().add(System.currentTimeMillis());
return entry.getKey();
}
}
return null;
}
private void cleanEntry(List<Long> entry) {
List<Long> toBeRemoved = new ArrayList<Long>();
for (long used: entry)
if (used < (System.currentTimeMillis() - periodMs))
toBeRemoved.add(used);
entry.removeAll(toBeRemoved);
}
}