Advertisement
Guest User

SlidingWindowMap code challenge FINAL

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