Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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;
- private long[] _times;
- private int _count;
- public SlidingWindowMap(Set<String> keys, int maxCount, long periodMs) {
- _keys = new String[keys.size()];
- keys.toArray(_keys);
- _maxCount = maxCount;
- _periodMs = periodMs;
- _times = 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 (_count == _times.length) {
- _count = 0;
- }
- long now = System.currentTimeMillis();
- if (now >= _times[_count] + _periodMs) {
- _times[_count] = now;
- return _keys[_count++ % _keys.length];
- }
- return null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement