import java.util.Set;
// Quick experiment of the SlidingWindowMap code challenge
// Author: Thierry Kormann - thierry.kormann@me.com
//
public class SlidingWindowMap {
private String[] _keys;
private int _maxCount;
private long _periodMs;
// Used to store when a key has been used.
private long[] _keyUsagesMs;
// An index in _keyUsagesMs to know when a key will be available.
private int _index;
public SlidingWindowMap(Set<String> keys, int maxCount, long periodMs) {
_keys = new String[keys.size()];
keys.toArray(_keys);
_maxCount = maxCount;
_periodMs = periodMs;
_keyUsagesMs = new long[keys.size() * maxCount];
}
/**
* @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() {
if (_index == _keyUsagesMs.length) {
_index = 0;
}
long now = System.currentTimeMillis();
if (now >= _keyUsagesMs[_index] + _periodMs) {
_keyUsagesMs[_index] = now;
return _keys[_index++ % _keys.length];
}
return null;
}
}