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.
26 package org.openecomp.sparky.analytics;
28 import java.util.concurrent.atomic.AtomicInteger;
31 * TODO: Fill in description.
35 public class AveragingRingBuffer {
37 private int numElements;
41 private AtomicInteger index;
45 private boolean initialAverageCalculated;
48 * Instantiates a new averaging ring buffer.
50 * @param size the size
52 public AveragingRingBuffer(int size) {
55 throw new IllegalArgumentException("Size must be greater than zero");
58 this.initialAverageCalculated = false;
59 this.numElements = size;
60 this.data = new long[this.numElements];
61 this.index = new AtomicInteger(-1);
67 * @param maxArrayIndex the max array index
69 private void calculateAverage(int maxArrayIndex) {
73 for (int i = 0; i <= maxArrayIndex; i++) {
77 average = (sum / (maxArrayIndex + 1));
81 public long getAvg() {
83 if (!initialAverageCalculated) {
85 * until the index rolls once we will calculate the average from the data that has been added
86 * to the array, not including the zero elements
88 if (index.get() < 0) {
91 calculateAverage(index.get());
102 * @param value the value
104 public synchronized void addSample(long value) {
106 index.incrementAndGet();
108 data[index.get()] = value;
110 if (index.get() == (numElements - 1)) {
111 calculateAverage(numElements - 1);
113 if (!initialAverageCalculated) {
114 initialAverageCalculated = true;