Advertisement
Guest User

SlidingWindowMap code challenge

a guest
Oct 4th, 2012
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.07 KB | None | 0 0
  1.  
  2. import java.util.Set;
  3.  
  4. // Quick experiment of the SlidingWindowMap code challenge
  5. // Author: Thierry Kormann - thierry.kormann@me.com
  6. public class SlidingWindowMap {
  7.  
  8.     private String[] _keys;
  9.     private int _maxCount;
  10.     private long _periodMs;
  11.  
  12.     private long[] _times;
  13.     private int _count;
  14.  
  15.     public SlidingWindowMap(Set<String> keys, int maxCount, long periodMs) {
  16.         _keys = new String[keys.size()];
  17.         keys.toArray(_keys);
  18.         _maxCount = maxCount;
  19.         _periodMs = periodMs;
  20.         _times = new long[keys.size() * maxCount];
  21.     }
  22.  
  23.     /**
  24.      * @return a key that has been used less than `maxCount` times during the
  25.      * past `periodMs` milliseconds or null if no such key exists.
  26.      */
  27.     public String getNextKey() {
  28.         if (_count == _times.length) {
  29.             _count = 0;
  30.         }
  31.         long now = System.currentTimeMillis();
  32.         if (now >= _times[_count] + _periodMs) {
  33.             _times[_count] = now;
  34.             return _keys[_count++ % _keys.length];
  35.         }
  36.         return null;
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement