sclass RollingAverage { int windowSize = 50; int recalcEvery = 1000; // to counter floating point errors int nRecalc; double sum; double[] list; int start, len; *() {} *(int *windowSize) {} synchronized void add(double d) { init(); if (++nRecalc >= recalcEvery) { nRecalc = 0; sum = 0; for i to len: sum += _get(i); } if (len == windowSize) { sum -= _get(0); len--; start = (start+1) % windowSize; } list[(start+len) % windowSize] = d; ++len; sum += d; } double _get(int i) { ret list[(start+i) % windowSize]; } synchronized double get() { init(); ret doubleRatio(sum, len); } void init { if (list == null) list = new double[windowSize]; } }