smithap

Untitled

Sep 23rd, 2012
114
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package test;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.HashMap;
  5. import java.util.Iterator;
  6. import java.util.List;
  7. import java.util.Map;
  8. import java.util.Map.Entry;
  9. import java.util.Set;
  10.  
  11. public class SlidingWindowMap {
  12.     private int maxCount;
  13.     private long periodMs;
  14.     private Map<String, List<Long>> usedBufferMap = new HashMap<String, List<Long>>();
  15.  
  16.     public SlidingWindowMap(Set<String> keys, int maxCount, long periodMs) {
  17.         Iterator<String> iterator = keys.iterator();
  18.         while(iterator.hasNext()){
  19.             String key = iterator.next();
  20.             usedBufferMap.put(key, new ArrayList<Long>());
  21.         }
  22.         this.maxCount = maxCount;
  23.         this.periodMs = periodMs;
  24.     }
  25.  
  26.     /**
  27.      * @return a key that has been used less than `maxCount` times during the
  28.      *         past `periodMs` milliseconds or null if no such key exists.
  29.      */
  30.     public String getNextKey() {
  31.         for (Entry<String, List<Long>> entry: usedBufferMap.entrySet()){
  32.             cleanEntry(entry.getValue());
  33.             if (entry.getValue().size() < maxCount) {
  34.                 entry.getValue().add(System.currentTimeMillis());
  35.                 return entry.getKey();
  36.             }
  37.         }
  38.         return null;
  39.     }
  40.  
  41.     private void cleanEntry(List<Long> entry) {
  42.         List<Long> toBeRemoved = new ArrayList<Long>();
  43.         for (long used: entry)
  44.             if (used < (System.currentTimeMillis() - periodMs))
  45.                 toBeRemoved.add(used);
  46.         entry.removeAll(toBeRemoved);
  47.     }
  48. }
RAW Paste Data