Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
 package com.codahale.metrics;
 
A Reservoir implementation backed by a sliding window that stores only the measurements made in the last N seconds (or other time unit).
public class SlidingTimeWindowReservoir implements Reservoir {
    // allow for this many duplicate ticks before overwriting measurements
    private static final int COLLISION_BUFFER = 256;
    // only trim on updating once every N
    private static final int TRIM_THRESHOLD = 256;
    private final Clock clock;
    private final ConcurrentSkipListMap<LongLongmeasurements;
    private final long window;
    private final AtomicLong lastTick;
    private final AtomicLong count;

    
Creates a new SlidingTimeWindowReservoir with the given window of time.

Parameters:
window the window of time
windowUnit the unit of window
    public SlidingTimeWindowReservoir(long windowTimeUnit windowUnit) {
        this(windowwindowUnit, Clock.defaultClock());
    }

    
Creates a new SlidingTimeWindowReservoir with the given clock and window of time.

Parameters:
window the window of time
windowUnit the unit of window
clock the Clock to use
    public SlidingTimeWindowReservoir(long windowTimeUnit windowUnitClock clock) {
        this. = clock;
        this. = new ConcurrentSkipListMap<LongLong>();
        this. = windowUnit.toNanos(window) * ;
        this. = new AtomicLong();
        this. = new AtomicLong();
    }
    @Override
    public int size() {
        trim();
        return .size();
    }
    @Override
    public void update(long value) {
        if (.incrementAndGet() %  == 0) {
            trim();
        }
        .put(getTick(), value);
    }
    @Override
    public Snapshot getSnapshot() {
        trim();
        return new Snapshot(.values());
    }
    private long getTick() {
        for (; ; ) {
            final long oldTick = .get();
            final long tick = .getTick() * ;
            // ensure the tick is strictly incrementing even if there are duplicate ticks
            final long newTick = tick > oldTick ? tick : oldTick + 1;
            if (.compareAndSet(oldTicknewTick)) {
                return newTick;
            }
        }
    }
    private void trim() {
        .headMap(getTick() - ).clear();
    }
New to GrepCode? Check out our FAQ X