Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
 package com.yammer.metrics.stats;
 
 import java.util.List;
A random sample of a stream of longs. Uses Vitter's Algorithm R to produce a statistically representative sample.

See also:
Random Sampling with a Reservoir
public class UniformSample implements Sample {
    private static final int BITS_PER_LONG = 63;
    private final AtomicLong count = new AtomicLong();
    private final AtomicLongArray values;

    
Creates a new UniformSample.

Parameters:
reservoirSize the number of samples to keep in the sampling reservoir
    public UniformSample(int reservoirSize) {
        this. = new AtomicLongArray(reservoirSize);
        clear();
    }
    @Override
    public void clear() {
        for (int i = 0; i < .length(); i++) {
            .set(i, 0);
        }
        .set(0);
    }
    @Override
    public int size() {
        final long c = .get();
        if (c > .length()) {
            return .length();
        }
        return (intc;
    }
    @Override
    public void update(long value) {
        final long c = .incrementAndGet();
        if (c <= .length()) {
            .set((intc - 1, value);
        } else {
            final long r = nextLong(c);
            if (r < .length()) {
                .set((intrvalue);
            }
        }
    }

    
Get a pseudo-random long uniformly between 0 and n-1. Stolen from java.util.Random.nextInt().

Parameters:
n the bound
Returns:
a value select randomly from the range [0..n).
    private static long nextLong(long n) {
        long bitsval;
        do {
            bits = ThreadLocalRandom.current().nextLong() & (~(1L << ));
            val = bits % n;
        } while (bits - val + (n - 1) < 0L);
        return val;
    }
    @Override
    public Snapshot getSnapshot() {
        final int s = size();
        final List<Longcopy = new ArrayList<Long>(s);
        for (int i = 0; i < si++) {
            copy.add(.get(i));
        }
        return new Snapshot(copy);
    }
New to GrepCode? Check out our FAQ X