2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * Copyright © 2017-2018 Amdocs
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
21 package org.onap.aai.sparky.analytics;
23 import java.util.concurrent.atomic.AtomicInteger;
26 * TODO: Fill in description.
30 public class AveragingRingBuffer {
32 private int numElements;
36 private AtomicInteger index;
40 private boolean initialAverageCalculated;
43 * Instantiates a new averaging ring buffer.
45 * @param size the size
47 public AveragingRingBuffer(int size) {
50 throw new IllegalArgumentException("Size must be greater than zero");
53 this.initialAverageCalculated = false;
54 this.numElements = size;
55 this.data = new long[this.numElements];
56 this.index = new AtomicInteger(-1);
62 * @param maxArrayIndex the max array index
64 private void calculateAverage(int maxArrayIndex) {
68 for (int i = 0; i <= maxArrayIndex; i++) {
72 average = (sum / (maxArrayIndex + 1));
76 public long getAvg() {
78 if (!initialAverageCalculated) {
80 * until the index rolls once we will calculate the average from the data that has been added
81 * to the array, not including the zero elements
83 if (index.get() < 0) {
86 calculateAverage(index.get());
97 * @param value the value
99 public synchronized void addSample(long value) {
101 index.incrementAndGet();
103 data[index.get()] = value;
105 if (index.get() == (numElements - 1)) {
106 calculateAverage(numElements - 1);
108 if (!initialAverageCalculated) {
109 initialAverageCalculated = true;