blob: 23254ad21345e52a3910d726977e799cd14e7f9a [file] [log] [blame]
Jonathan Hart233a18a2015-03-02 17:24:58 -08001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2015-present Open Networking Laboratory
Jonathan Hart233a18a2015-03-02 17:24:58 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onlab.util;
17
18import java.util.ArrayList;
19import java.util.Collections;
20import java.util.List;
Jonathan Hart233a18a2015-03-02 17:24:58 -080021import java.util.concurrent.ScheduledExecutorService;
22import java.util.concurrent.TimeUnit;
23import java.util.concurrent.atomic.AtomicLong;
24import java.util.stream.Collectors;
25
26import static com.google.common.base.Preconditions.checkArgument;
Yuta HIGUCHI1624df12016-07-21 16:54:33 -070027import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
28import static org.onlab.util.Tools.groupedThreads;
Jonathan Hart233a18a2015-03-02 17:24:58 -080029
30/**
31 * Maintains a sliding window of value counts. The sliding window counter is
32 * initialized with a number of window slots. Calls to #incrementCount() will
33 * increment the value in the current window slot. Periodically the window
34 * slides and the oldest value count is dropped. Calls to #get() will get the
35 * total count for the last N window slots.
36 */
37public final class SlidingWindowCounter {
38
39 private volatile int headSlot;
40 private final int windowSlots;
41
42 private final List<AtomicLong> counters;
43
44 private final ScheduledExecutorService background;
45
46 private static final int SLIDE_WINDOW_PERIOD_SECONDS = 1;
47
48 /**
49 * Creates a new sliding window counter with the given total number of
50 * window slots.
51 *
52 * @param windowSlots total number of window slots
53 */
54 public SlidingWindowCounter(int windowSlots) {
55 checkArgument(windowSlots > 0, "Window size must be a positive integer");
56
57 this.windowSlots = windowSlots;
58 this.headSlot = 0;
59
60 // Initialize each item in the list to an AtomicLong of 0
61 this.counters = Collections.nCopies(windowSlots, 0)
Thomas Vachuskab0317c62015-04-08 23:58:58 -070062 .stream()
63 .map(AtomicLong::new)
64 .collect(Collectors.toCollection(ArrayList::new));
Jonathan Hart233a18a2015-03-02 17:24:58 -080065
Yuta HIGUCHI1624df12016-07-21 16:54:33 -070066 background = newSingleThreadScheduledExecutor(groupedThreads("SlidingWindowCounter", "bg-%d"));
Jonathan Hart233a18a2015-03-02 17:24:58 -080067 background.scheduleWithFixedDelay(this::advanceHead, 0,
Thomas Vachuskab0317c62015-04-08 23:58:58 -070068 SLIDE_WINDOW_PERIOD_SECONDS, TimeUnit.SECONDS);
Jonathan Hart233a18a2015-03-02 17:24:58 -080069 }
70
71 /**
72 * Releases resources used by the SlidingWindowCounter.
73 */
74 public void destroy() {
75 background.shutdownNow();
76 }
77
78 /**
79 * Increments the count of the current window slot by 1.
80 */
81 public void incrementCount() {
82 incrementCount(headSlot, 1);
83 }
84
85 /**
86 * Increments the count of the current window slot by the given value.
87 *
88 * @param value value to increment by
89 */
90 public void incrementCount(long value) {
91 incrementCount(headSlot, value);
92 }
93
94 private void incrementCount(int slot, long value) {
95 counters.get(slot).addAndGet(value);
96 }
97
98 /**
99 * Gets the total count for the last N window slots.
100 *
101 * @param slots number of slots to include in the count
102 * @return total count for last N slots
103 */
104 public long get(int slots) {
105 checkArgument(slots <= windowSlots,
106 "Requested window must be less than the total window slots");
107
108 long sum = 0;
109
110 for (int i = 0; i < slots; i++) {
111 int currentIndex = headSlot - i;
112 if (currentIndex < 0) {
113 currentIndex = counters.size() + currentIndex;
114 }
115 sum += counters.get(currentIndex).get();
116 }
117
118 return sum;
119 }
120
121 void advanceHead() {
122 counters.get(slotAfter(headSlot)).set(0);
123 headSlot = slotAfter(headSlot);
124 }
125
126 private int slotAfter(int slot) {
127 return (slot + 1) % windowSlots;
128 }
129
130}