01: /* Copyright 2005 The JA-SIG Collaborative. All rights reserved.
02: * See license distributed with this file and
03: * available online at http://www.uportal.org/license.html
04: */
05:
06: package org.jasig.portal.utils;
07:
08: /**
09: * @author George Lindholm <a href="mailto:George.Lindholm@ubc.ca">George.Lindholm@ubc.ca</a>
10: * @version $Revision: 36731 $ $Date: 2006-09-27 11:21:06 -0700 (Wed, 27 Sep 2006) $
11: * @since uPortal 2.5
12: */
13: public class MovingAverage {
14:
15: public static final int SAMPLESIZE = 100;
16: private long[] samples;
17: private int ent = -1;
18: private long sum = 0;
19: private long totalSamples = 0;
20: private long highMax = 0;
21:
22: public MovingAverage() {
23: samples = new long[SAMPLESIZE];
24: }
25:
26: public synchronized MovingAverageSample add(final long sample) {
27:
28: final long lastSample = sample;
29: final int first = ++ent % samples.length;
30: if (totalSamples >= samples.length) {
31: sum -= samples[first]; // We've wrapped, so we can remove the 'first' entry
32: }
33: sum += sample;
34: samples[first] = sample;
35: if (sample > highMax) {
36: highMax = sample;
37: }
38: totalSamples++;
39:
40: long max = 0;
41: long min = Long.MAX_VALUE;
42: final long arraySize = Math.min(totalSamples, samples.length);
43: for (int i = 0; i < arraySize; i++) {
44: if (samples[i] > max) {
45: max = samples[i];
46: }
47: if (samples[i] < min) {
48: min = samples[i];
49: }
50: }
51:
52: return new MovingAverageSample(sum / arraySize, highMax,
53: lastSample, max, min, totalSamples);
54: }
55: }
|