2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6 * Copyright © 2017 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 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
23 package org.onap.aai.sparky.analytics;
25 import java.util.concurrent.atomic.AtomicInteger;
28 * TODO: Fill in description.
32 public class AveragingRingBuffer {
34 private int numElements;
38 private AtomicInteger index;
42 private boolean initialAverageCalculated;
45 * Instantiates a new averaging ring buffer.
47 * @param size the size
49 public AveragingRingBuffer(int size) {
52 throw new IllegalArgumentException("Size must be greater than zero");
55 this.initialAverageCalculated = false;
56 this.numElements = size;
57 this.data = new long[this.numElements];
58 this.index = new AtomicInteger(-1);
64 * @param maxArrayIndex the max array index
66 private void calculateAverage(int maxArrayIndex) {
70 for (int i = 0; i <= maxArrayIndex; i++) {
74 average = (sum / (maxArrayIndex + 1));
78 public long getAvg() {
80 if (!initialAverageCalculated) {
82 * until the index rolls once we will calculate the average from the data that has been added
83 * to the array, not including the zero elements
85 if (index.get() < 0) {
88 calculateAverage(index.get());
99 * @param value the value
101 public synchronized void addSample(long value) {
103 index.incrementAndGet();
105 data[index.get()] = value;
107 if (index.get() == (numElements - 1)) {
108 calculateAverage(numElements - 1);
110 if (!initialAverageCalculated) {
111 initialAverageCalculated = true;