Elffuss BraidHub

kikocis/java-driver public

Add RollingCount
Changesetbd5e396c06272fa3da61cda853f7a9ea5bc11aa36ba0a26be06b24f452a1593c
Authorolim7t <omichallat+github@gmail.com> · 2016-07-22 00:35 -07:00
Committerolim7t <omichallat+github@gmail.com> · 2016-07-27 10:01 -07:00
Parentse0b1e4942e30

Browse the files at this changeset

3 files changed

added driver-core/src/main/java/com/datastax/driver/core/policies/Clock.java +27 −0
@@ -0,0 +1,27 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
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 com.datastax.driver.core.policies;
17+
18+/**
19+ * Wraps System.nanoTime() to make it easy to mock in tests.
20+ */
21+class Clock {
22+ static final Clock DEFAULT = new Clock();
23+
24+ long nanoTime() {
25+ return System.nanoTime();
26+ }
27+}
added driver-core/src/main/java/com/datastax/driver/core/policies/RollingCount.java +118 −0
@@ -0,0 +1,118 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
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 com.datastax.driver.core.policies;
17+
18+import java.util.concurrent.TimeUnit;
19+import java.util.concurrent.atomic.AtomicLong;
20+import java.util.concurrent.atomic.AtomicLongArray;
21+import java.util.concurrent.atomic.AtomicReference;
22+
23+/**
24+ * A "rolling" count over a 1-minute sliding window.
25+ */
26+class RollingCount {
27+ // Divide the minute into 5-second intervals
28+ private static final long INTERVAL_SIZE = TimeUnit.SECONDS.toNanos(5);
29+
30+ // A circular buffer containing the counts over the 12 previous intervals. Their sum is the count we're looking for.
31+ // If we're at t = 61s this would span [0,60[
32+ private final AtomicLongArray previousIntervals = new AtomicLongArray(12);
33+ // The interval we're currently recording events for. It hasn't completed yet, so it's not included in the count.
34+ // If we're at t = 61s this would span [60,65[
35+ // Note that we don't expect very high concurrency on RollingCount (it's used to count errors), so AtomicLong is
36+ // good enough here.
37+ private final AtomicLong currentInterval = new AtomicLong();
38+ // Other mutable state, grouped in an object for atomic updates
39+ private final AtomicReference<State> state;
40+ private final Clock clock;
41+
42+ RollingCount(Clock clock) {
43+ this.state = new AtomicReference<State>(new State(clock.nanoTime()));
44+ this.clock = clock;
45+ }
46+
47+ void increment() {
48+ add(1);
49+ }
50+
51+ void add(long amount) {
52+ tickIfNecessary();
53+ currentInterval.addAndGet(amount);
54+ }
55+
56+ long get() {
57+ tickIfNecessary();
58+ return state.get().totalCount;
59+ }
60+
61+ private void tickIfNecessary() {
62+ State oldState = state.get();
63+ long newTick = clock.nanoTime();
64+ long age = newTick - oldState.lastTick;
65+ if (age >= INTERVAL_SIZE) {
66+ long currentCount = currentInterval.get();
67+
68+ long newIntervalStartTick = newTick - age % INTERVAL_SIZE;
69+ long elapsedIntervals = Math.min(age / INTERVAL_SIZE, 12);
70+ int newOffset = (int) ((oldState.offset + elapsedIntervals) % 12);
71+
72+ long newTotal;
73+ if (elapsedIntervals == 12) {
74+ // We wrapped around the circular buffer, all our values are stale
75+ // Don't mutate previousIntervals yet because this part of the code is still multi-threaded.
76+ newTotal = 0;
77+ } else {
78+ // Add the current interval that just completed
79+ newTotal = oldState.totalCount + currentCount;
80+ // Subtract all elapsed intervals: they're either idle ones, or the one at the old offset that we're
81+ // about to replace
82+ for (int i = 1; i <= elapsedIntervals; i++) {
83+ newTotal -= previousIntervals.get((newOffset + 12 - i) % 12);
84+ }
85+ }
86+
87+ State newState = new State(newIntervalStartTick, newOffset, newTotal);
88+ if (state.compareAndSet(oldState, newState)) {
89+ // Only one thread gets here, so we can now:
90+ // - reset the current count (don't use reset because other threads might already have started updating
91+ // it)
92+ currentInterval.addAndGet(-currentCount);
93+ // - store the interval that just completed (or clear it if we wrapped)
94+ previousIntervals.set(oldState.offset, elapsedIntervals < 12 ? currentCount : 0);
95+ // - clear any idle interval
96+ for (int i = 1; i < elapsedIntervals; i++) {
97+ previousIntervals.set((newOffset + 12 - i) % 12, 0);
98+ }
99+ }
100+ }
101+ }
102+
103+ static class State {
104+ final long lastTick; // last time the state was modified
105+ final int offset; // the offset that the current interval will replace once it's complete
106+ final long totalCount; // cache of sum(previousIntervals)
107+
108+ State(long lastTick) {
109+ this(lastTick, 0, 0);
110+ }
111+
112+ State(long lastTick, int offset, long totalCount) {
113+ this.lastTick = lastTick;
114+ this.offset = offset;
115+ this.totalCount = totalCount;
116+ }
117+ }
118+}
added driver-core/src/test/java/com/datastax/driver/core/policies/RollingCountTest.java +149 −0
@@ -0,0 +1,149 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
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 com.datastax.driver.core.policies;
17+
18+import org.mockito.Mock;
19+import org.mockito.MockitoAnnotations;
20+import org.testng.annotations.BeforeMethod;
21+import org.testng.annotations.Test;
22+
23+import java.util.concurrent.TimeUnit;
24+
25+import static com.datastax.driver.core.Assertions.assertThat;
26+import static java.util.concurrent.TimeUnit.NANOSECONDS;
27+import static java.util.concurrent.TimeUnit.SECONDS;
28+import static org.mockito.Mockito.when;
29+
30+public class RollingCountTest {
31+ @Mock
32+ Clock clock;
33+
34+ RollingCount rollingCount;
35+
36+ @BeforeMethod(groups = "unit")
37+ public void setup() {
38+ MockitoAnnotations.initMocks(this);
39+ assertThat(clock.nanoTime()).isEqualTo(0);
40+ rollingCount = new RollingCount(clock);
41+ }
42+
43+ @Test(groups = "unit")
44+ public void should_record_adds_in_first_interval() {
45+ // t = 0
46+ rollingCount.increment();
47+ setTime(1, SECONDS);
48+ rollingCount.increment();
49+ setTime(2, SECONDS);
50+ rollingCount.increment();
51+
52+ // the count does not update in real time...
53+ assertThat(rollingCount.get()).isEqualTo(0);
54+
55+ // but only at the end of each 5-second interval
56+ setTime(5, SECONDS);
57+ assertThat(rollingCount.get()).isEqualTo(3);
58+ }
59+
60+ @Test(groups = "unit")
61+ public void should_record_adds_over_two_intervals() {
62+ rollingCount.add(2);
63+
64+ setTime(5, SECONDS); // 2nd interval
65+ rollingCount.add(3);
66+
67+ setTime(10, SECONDS);
68+ assertThat(rollingCount.get()).isEqualTo(5);
69+ }
70+
71+ @Test(groups = "unit")
72+ public void should_record_adds_separated_by_idle_intervals() {
73+ rollingCount.add(2);
74+
75+ setTime(10, SECONDS); // 3rd interval
76+ rollingCount.add(3);
77+
78+ setTime(15, SECONDS);
79+ assertThat(rollingCount.get()).isEqualTo(5);
80+ }
81+
82+ @Test(groups = "unit")
83+ public void should_rotate() {
84+ // 2 in [0,5[, then 1 every 5 seconds in [5,60[
85+ rollingCount.add(2);
86+ for (int i = 1; i < 12; i++) {
87+ setTime(i * 5, SECONDS);
88+ rollingCount.add(1);
89+ }
90+ setTime(60, SECONDS);
91+ // the previous minute is now [0,60[
92+ assertThat(rollingCount.get()).isEqualTo(13);
93+
94+ rollingCount.add(1);
95+ setTime(65, SECONDS);
96+ // the previous minute is now [5,65[, so the 2 events from [0,5[ should be forgotten
97+ assertThat(rollingCount.get()).isEqualTo(12);
98+ }
99+
100+ @Test(groups = "unit")
101+ public void should_rotate_with_idle_intervals() {
102+ // 1 every 5 seconds in [0,60[
103+ for (int i = 0; i < 12; i++) {
104+ setTime(i * 5, SECONDS);
105+ rollingCount.add(1);
106+ }
107+ // idle in [60, 75[, then 1 in [75,80[
108+ setTime(75, SECONDS);
109+ rollingCount.add(1);
110+
111+ setTime(80, SECONDS);
112+ // the last minute is [20,80[, with 1 every 5 seconds except during 15 seconds
113+ assertThat(rollingCount.get()).isEqualTo(9);
114+ }
115+
116+ @Test(groups = "unit")
117+ public void should_rotate_when_idle_for_full_period() {
118+ // 1 every 5 seconds in [0,60[
119+ for (int i = 0; i < 12; i++) {
120+ setTime(i * 5, SECONDS);
121+ rollingCount.add(1);
122+ }
123+ // idle for the next minute [60,120[, then 1 in [120,125[
124+ setTime(120, SECONDS);
125+ rollingCount.add(1);
126+
127+ setTime(125, SECONDS);
128+ assertThat(rollingCount.get()).isEqualTo(1);
129+ }
130+
131+ @Test(groups = "unit")
132+ public void should_rotate_when_idle_for_more_than_full_period() {
133+ // 1 every 5 seconds in [0,60[
134+ for (int i = 0; i < 12; i++) {
135+ setTime(i * 5, SECONDS);
136+ rollingCount.add(1);
137+ }
138+ // idle for the next minute and 5 seconds [60,125[, then 1 in [125,130[
139+ setTime(125, SECONDS);
140+ rollingCount.add(1);
141+
142+ setTime(130, SECONDS);
143+ assertThat(rollingCount.get()).isEqualTo(1);
144+ }
145+
146+ private void setTime(long time, TimeUnit unit) {
147+ when(clock.nanoTime()).thenReturn(NANOSECONDS.convert(time, unit));
148+ }
149+}