Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.malagasys.slidingwindow;
- import java.util.ArrayDeque;
- import java.util.Deque;
- class SlidingWindow {
- /**
- * Keep track of all of the timestamp of the call.
- */
- private final Deque<Long> callsTimestamp = new ArrayDeque<>();
- /** Width of the window in millisecond. */
- private final long width;
- /** The maximum number of call within the window. */
- private final int maxCount;
- /** Current time of the window */
- private long currentTime;
- SlidingWindow(long width, int maxCall) {
- this.width = width;
- this.maxCount = maxCall;
- }
- /**
- * Log a call occuring at the given timestamp.
- * @param timestamp
- */
- public void logcall(long timestamp) {
- if (callsTimestamp.size() >= maxCount) {
- throw new IllegalStateException("Maximum number of call reached.");
- }
- callsTimestamp.add(timestamp);
- }
- public boolean isFull() {
- return callsTimestamp.size() == maxCount;
- }
- /**
- * Slide the window so that the end of the window matches the given timestamp.
- */
- public void slideTo(long currentTimestamp) {
- currentTime = currentTimestamp;
- long windowLeft = currentTime - width;
- //Strip methodcalls that fall out of the window from the head of the queue.
- boolean stop = false;
- do {
- Long first = callsTimestamp.peekFirst();
- if (first == null || first >= windowLeft) {
- stop = true;
- } else {
- if (first != null) {
- //this call falls out the window ==> remove it.
- callsTimestamp.removeFirst();
- }
- }
- } while (!stop);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement