2 * ============LICENSE_START===================================================
3 * SPARKY (AAI UI service)
4 * ============================================================================
5 * Copyright © 2017 AT&T Intellectual Property.
6 * Copyright © 2017 Amdocs
8 * ============================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 * ============LICENSE_END=====================================================
22 * ECOMP and OpenECOMP are trademarks
23 * and service marks of AT&T Intellectual Property.
25 package org.onap.aai.sparky.analytics;
27 import java.util.concurrent.atomic.AtomicInteger;
30 * TODO: Fill in description.
34 public class AveragingRingBuffer {
36 private int numElements;
40 private AtomicInteger index;
44 private boolean initialAverageCalculated;
47 * Instantiates a new averaging ring buffer.
49 * @param size the size
51 public AveragingRingBuffer(int size) {
54 throw new IllegalArgumentException("Size must be greater than zero");
57 this.initialAverageCalculated = false;
58 this.numElements = size;
59 this.data = new long[this.numElements];
60 this.index = new AtomicInteger(-1);
66 * @param maxArrayIndex the max array index
68 private void calculateAverage(int maxArrayIndex) {
72 for (int i = 0; i <= maxArrayIndex; i++) {
76 average = (sum / (maxArrayIndex + 1));
80 public long getAvg() {
82 if (!initialAverageCalculated) {
84 * until the index rolls once we will calculate the average from the data that has been added
85 * to the array, not including the zero elements
87 if (index.get() < 0) {
90 calculateAverage(index.get());
101 * @param value the value
103 public synchronized void addSample(long value) {
105 index.incrementAndGet();
107 data[index.get()] = value;
109 if (index.get() == (numElements - 1)) {
110 calculateAverage(numElements - 1);
112 if (!initialAverageCalculated) {
113 initialAverageCalculated = true;