raherygasy

SlidingWindowMap - File One

Sep 5th, 2012
91
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package com.malagasys.slidingwindow;
  2.  
  3. import java.util.ArrayDeque;
  4. import java.util.Deque;
  5.  
  6. class SlidingWindow {
  7.     /**
  8.      * Keep track of all of the timestamp of the call.
  9.      */
  10.     private final Deque<Long> callsTimestamp = new ArrayDeque<>();
  11.  
  12.     /** Width of the window in millisecond. */
  13.     private final long width;
  14.    
  15.     /** The maximum number of call within the window. */
  16.     private final int maxCount;
  17.    
  18.     /** Current time of the window */
  19.     private long currentTime;
  20.    
  21.     SlidingWindow(long width, int maxCall) {
  22.         this.width = width;
  23.         this.maxCount = maxCall;
  24.     }
  25.    
  26.     /**
  27.      * Log a call occuring at the given timestamp.
  28.      * @param timestamp
  29.      */
  30.     public void logcall(long timestamp) {
  31.         if (callsTimestamp.size() >= maxCount) {
  32.             throw new IllegalStateException("Maximum number of call reached.");
  33.         }
  34.         callsTimestamp.add(timestamp);
  35.     }
  36.    
  37.     public boolean isFull() {
  38.         return callsTimestamp.size() == maxCount;
  39.     }
  40.    
  41.     /**
  42.      * Slide the window so that the end of the window matches the given timestamp.
  43.      */
  44.     public void slideTo(long currentTimestamp) {
  45.         currentTime = currentTimestamp;
  46.         long windowLeft = currentTime - width;
  47.        
  48.         //Strip methodcalls that fall out of the window from the head of the queue.
  49.         boolean stop = false;
  50.         do {
  51.             Long first = callsTimestamp.peekFirst();
  52.             if (first == null || first >= windowLeft) {
  53.                 stop = true;
  54.             } else {
  55.                 if (first != null) {
  56.                     //this call falls out the window ==> remove it.
  57.                     callsTimestamp.removeFirst();
  58.                 }
  59.             }
  60.         } while (!stop);
  61.     }
  62. }
RAW Paste Data