Import atomix/{storage,utils}
[controller.git] / third-party / atomix / utils / src / main / java / io / atomix / utils / misc / SlidingWindowCounter.java
1 /*
2  * Copyright 2015-present Open Networking Foundation
3  *
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  */
16 package io.atomix.utils.misc;
17
18 import io.atomix.utils.concurrent.Scheduled;
19 import io.atomix.utils.concurrent.SingleThreadContext;
20 import io.atomix.utils.concurrent.ThreadContext;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23
24 import java.util.ArrayList;
25 import java.util.Collections;
26 import java.util.List;
27 import java.util.concurrent.TimeUnit;
28 import java.util.concurrent.atomic.AtomicLong;
29 import java.util.stream.Collectors;
30
31 import static com.google.common.base.Preconditions.checkArgument;
32
33 /**
34  * Maintains a sliding window of value counts. The sliding window counter is
35  * initialized with a number of window slots. Calls to #incrementCount() will
36  * increment the value in the current window slot. Periodically the window
37  * slides and the oldest value count is dropped. Calls to #get() will get the
38  * total count for the last N window slots.
39  */
40 public final class SlidingWindowCounter {
41   private final Logger log = LoggerFactory.getLogger(getClass());
42   private volatile int headSlot;
43   private final int windowSlots;
44
45   private final List<AtomicLong> counters;
46
47   private final Scheduled schedule;
48
49   private static final int SLIDE_WINDOW_PERIOD_SECONDS = 1;
50
51   public SlidingWindowCounter(int windowSlots) {
52     this(windowSlots, new SingleThreadContext("sliding-window-counter-%d"));
53   }
54
55   /**
56    * Creates a new sliding window counter with the given total number of
57    * window slots.
58    *
59    * @param windowSlots total number of window slots
60    */
61   public SlidingWindowCounter(int windowSlots, ThreadContext context) {
62     checkArgument(windowSlots > 0, "Window size must be a positive integer");
63
64     this.windowSlots = windowSlots;
65     this.headSlot = 0;
66
67     // Initialize each item in the list to an AtomicLong of 0
68     this.counters = Collections.nCopies(windowSlots, 0)
69         .stream()
70         .map(AtomicLong::new)
71         .collect(Collectors.toCollection(ArrayList::new));
72     this.schedule = context.schedule(0, SLIDE_WINDOW_PERIOD_SECONDS, TimeUnit.SECONDS, this::advanceHead);
73   }
74
75   /**
76    * Releases resources used by the SlidingWindowCounter.
77    */
78   public void destroy() {
79     schedule.cancel();
80   }
81
82   /**
83    * Increments the count of the current window slot by 1.
84    */
85   public void incrementCount() {
86     incrementCount(headSlot, 1);
87   }
88
89   /**
90    * Increments the count of the current window slot by the given value.
91    *
92    * @param value value to increment by
93    */
94   public void incrementCount(long value) {
95     incrementCount(headSlot, value);
96   }
97
98   private void incrementCount(int slot, long value) {
99     counters.get(slot).addAndGet(value);
100   }
101
102   /**
103    * Gets the total count for the last N window slots.
104    *
105    * @param slots number of slots to include in the count
106    * @return total count for last N slots
107    */
108   public long get(int slots) {
109     checkArgument(slots <= windowSlots,
110         "Requested window must be less than the total window slots");
111
112     long sum = 0;
113
114     for (int i = 0; i < slots; i++) {
115       int currentIndex = headSlot - i;
116       if (currentIndex < 0) {
117         currentIndex = counters.size() + currentIndex;
118       }
119       sum += counters.get(currentIndex).get();
120     }
121
122     return sum;
123   }
124
125   void advanceHead() {
126     counters.get(slotAfter(headSlot)).set(0);
127     headSlot = slotAfter(headSlot);
128   }
129
130   private int slotAfter(int slot) {
131     return (slot + 1) % windowSlots;
132   }
133
134 }