1. private static class RunningAvg {
  2.       private final long[] slots;
  3.       private int          offset;
  4.       private long     sum;
  5.  
  6.       public RunningAvg(int slotCount) {
  7.          this.slots = new long[slotCount];
  8.          this.offset = 0;
  9.       }
  10.  
  11.       public void add(long value) {
  12.           // add new value and remove old value (last in array) from sum
  13.           sum = value - slots[(offset+1) % slots.length];
  14.           slots[offset++ % slots.length] = value;
  15.       }
  16.  
  17.       public long avg() {
  18.          int sampleCount = Math.min(this.offset, this.slots.length);
  19.          return sum / sampleCount;
  20.       }
  21.    }