package com.codahale.metrics;

import static java.lang.Math.min;

/**
 * A {@link Reservoir} implementation backed by a sliding window that stores the last {@code N}
 * measurements.
 */
public class SlidingWindowReservoir implements Reservoir {
    private final long[] measurements;
    private long count;

    /**
     * Creates a new {@link SlidingWindowReservoir} which stores the last {@code size} measurements.
     *
     * @param size the number of measurements to store
     */
    public SlidingWindowReservoir(int size) {
        this.measurements = new long[size];
        this.count = 0;
    }

    @Override
    public synchronized int size() {
        return (int) min(count, measurements.length);
    }

    @Override
    public synchronized void update(long value) {
        measurements[((int) count++ % measurements.length)] = value;
    }

    @Override
    public Snapshot getSnapshot() {
        final long[] values = new long[size()];
        for (int i = 0; i < values.length; i++) {
            synchronized (this) {
                values[i] = measurements[i];
            }
        }
        return new Snapshot(values);
    }
}

@@ -239,20 +239,17 @@
 rvoir %7B%0A
-    
+%09
 private 
@@ -275,16 +275,48 @@
 ements;%0A
+    private boolean fullWindow;%0A
     priv
@@ -683,28 +683,93 @@
 ize() %7B%0A    
-    
+%09if(fullWindow)%7B%0A    %09%09return measurements.length;%0A    %09%7Delse%7B%0A    %09%09
 return (int)
@@ -802,16 +802,23 @@
 ength);%0A
+    %09%7D%0A
     %7D%0A%0A 
@@ -902,17 +902,16 @@
 ements%5B(
-(
 int) cou
@@ -918,41 +918,106 @@
 nt++
- %25 measurements.length)%5D = value;
+%5D = value;%0A    %09if(count %3E= measurements.length)%7B%0A    %09%09count = 0;%0A    %09%09fullWindow = true;%0A    %09%7D
 %0A   

Fix for ArrayOutOfBoundsException if reservoir has too many samples and causes integer overflow.