package com.codahale.metrics;

import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicLongArray;

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 AtomicLongArray measurements;
    private final AtomicLong 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 AtomicLongArray(size);
        this.count = new AtomicLong();
    }

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

    @Override
    public void update(long value) {
        final int i = (int) (count.getAndIncrement() % measurements.length());
        measurements.set(i, value);
    }

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

@@ -422,16 +422,55 @@
 g count;
+%0A    private final AtomicLong sequence;
 %0A%0A    /*
@@ -782,16 +782,58 @@
 Long();%0A
+        this.sequence = new AtomicLong();%0A
     %7D%0A%0A 
@@ -1100,24 +1100,60 @@
 (i, value);%0A
+        sequence.incrementAndGet();%0A
     %7D%0A%0A    @
@@ -1193,24 +1193,110 @@
 napshot() %7B%0A
+        while(count.get() != sequence.get()) %7B%0A            Thread.yield();%0A        %7D%0A%0A
         fina

Add a second barrier to SlidingWindowReservoir.