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 AtomicLong index;
    private final AtomicLong count;
    private final AtomicLongArray measurements;

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

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

    @Override
    public void update(long value) {
        // first, get and increment the index
        final int n = (int) (index.getAndIncrement() % measurements.length());
        // second, set the measurement
        measurements.set(n, value);
        // third, increment the count of written measurements
        count.incrementAndGet();
    }

    @Override
    public Snapshot getSnapshot() {
        // use size, not index, to prevent phantom reads
        final long[] values = new long[size()];
        for (int i = 0; i < values.length; i++) {
            values[i] = measurements.get(i);
        }
        return new Snapshot(values);
    }
}

@@ -866,24 +866,82 @@
 nt size() %7B%0A
+        // use count, not index, to prevent phantom reads%0A
         retu
@@ -1063,42 +1063,21 @@
  // 
-first, get and increment the index
+entry barrier
 %0A   
@@ -1091,23 +1091,17 @@
 nal 
-int
+long
  n = 
-(int) (
 inde
@@ -1119,16 +1119,50 @@
 rement()
+;%0A        final int idx = (int) (n
  %25 measu
@@ -1176,24 +1176,25 @@
 .length());%0A
+%0A
         // s
@@ -1196,35 +1196,24 @@
  // 
-second, set the measurement
+critical section
 %0A   
@@ -1234,17 +1234,19 @@
 nts.set(
-n
+idx
 , value)
@@ -1243,24 +1243,25 @@
 dx, value);%0A
+%0A
         // t
@@ -1263,205 +1263,331 @@
  // 
-third, increment the count of written measurements%0A        count.incrementAndGet();%0A    %7D%0A%0A    @Override%0A    public Snapshot getSnapshot() %7B%0A        // use size, not index, to prevent phantom reads
+exit barrier%0A        while (true) %7B%0A            // Only return once other writers (i.e., those who have already incremented index) have%0A            // incremented count.%0A            if (count.compareAndSet(n, n + 1)) %7B%0A                return;%0A            %7D%0A        %7D%0A    %7D%0A%0A    @Override%0A    public Snapshot getSnapshot() %7B
 %0A   

Fix the exit barrier in SlidingWindowReservoir.