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);
    }
}

@@ -24,16 +24,116 @@
 trics;%0A%0A
+import java.util.concurrent.atomic.AtomicLong;%0Aimport java.util.concurrent.atomic.AtomicLongArray;%0A%0A
 import s
@@ -235,32 +235,35 @@
  that stores the
+%0A *
  last %7B@code N%7D%0A
@@ -261,19 +261,16 @@
 @code N%7D
-%0A *
  measure
@@ -361,27 +361,60 @@
 nal 
-long%5B%5D measureme
+AtomicLong index;%0A    private final AtomicLong cou
 nt
-s
 ;%0A  
@@ -427,18 +427,42 @@
 ate 
-long cou
+final AtomicLongArray measureme
 nt
+s
 ;%0A%0A 
@@ -537,24 +537,31 @@
 res the last
+%0A     *
  %7B@code size
@@ -709,37 +709,71 @@
 his.
-measurements = new long%5Bsize%5D
+index = new AtomicLong();%0A        this.count = new AtomicLong()
 ;%0A  
@@ -787,17 +787,48 @@
 his.
-cou
+measureme
 nt
+s
  = 
-0
+new AtomicLongArray(size)
 ;%0A  
@@ -857,29 +857,16 @@
  public 
-synchronized 
 int size
@@ -900,16 +900,22 @@
 in(count
+.get()
 , measur
@@ -927,16 +927,18 @@
 s.length
+()
 );%0A    %7D
@@ -964,29 +964,16 @@
  public 
-synchronized 
 void upd
@@ -1002,67 +1002,293 @@
     
-measurements%5B((int) count++ %25 measurements.length)%5D = value
+// first, get and increment the index%0A        final int n = (int) (index.getAndIncrement() %25 measurements.length());%0A        // second, set the measurement%0A        measurements.set(n, value);%0A        // third, increment the count of written measurements%0A        count.incrementAndGet()
 ;%0A  
@@ -1338,24 +1338,81 @@
 napshot() %7B%0A
+        // use size, not index, to prevent phantom reads%0A
         fina
@@ -1501,46 +1501,8 @@
 ) %7B%0A
-            synchronized (this) %7B%0A    
     
@@ -1537,26 +1537,16 @@
 ents
-%5Bi%5D;%0A            %7D
+.get(i);
 %0A   

Switch to a two-barrier SlidingWindowReservoir.