raherygasy

SlidingWindowMap - File two

Sep 5th, 2012
78
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package com.malagasys.slidingwindow;
  2.  
  3. import java.util.Arrays;
  4. import java.util.HashMap;
  5. import java.util.HashSet;
  6. import java.util.Map;
  7. import java.util.Set;
  8.  
  9. public class SlidingWindowMap {
  10.     private final Map<String, SlidingWindow> map = new HashMap<>();
  11.    
  12.     public SlidingWindowMap(Set<String> keys, int maxCount, long periodMs) {
  13.         //Just create a sliding window per key.
  14.         for (String key : keys) {
  15.             map.put(key, new SlidingWindow(periodMs, maxCount));
  16.         }
  17.     }
  18.  
  19.     public String getNextKey() {
  20.         String nextKey = null;
  21.         long currentTime = System.currentTimeMillis();
  22.  
  23.         for (Map.Entry<String, SlidingWindow> e : map.entrySet()) {
  24.             //Slide the window to match current timestamp
  25.             e.getValue().slideTo(currentTime);
  26.            
  27.             //If the window is not full yet, accept the key as the next key
  28.             if (!e.getValue().isFull()) {
  29.                 e.getValue().logcall(currentTime);
  30.                 nextKey = e.getKey();
  31.                 break;
  32.             }
  33.         }
  34.        
  35.         return nextKey;
  36.     }
  37.    
  38.     //========= Run ============
  39.     public static void main(String[] args) throws Exception {
  40.         Set<String> keys = new HashSet<>(Arrays.asList("key_a", "key_b", "key_c", "key_d"));
  41.         SlidingWindowMap map = new SlidingWindowMap(keys, 5, 30000);
  42.        
  43.         for (int i = 0; i < 40; i++) {
  44.             System.out.println(map.getNextKey());
  45.             if (i%3 == 0) {
  46.                 Thread.sleep(5000);
  47.             }
  48.         }
  49.     }
  50. }
RAW Paste Data