Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
 package com.codahale.metrics;
 
 import java.util.List;
A random sampling reservoir 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 UniformReservoir implements Reservoir {
    private static final int DEFAULT_SIZE = 1028;
    private static final int BITS_PER_LONG = 63;
    private final AtomicLong count = new AtomicLong();
    private final AtomicLongArray values;

    
Creates a new UniformReservoir of 1028 elements, which offers a 99.9% confidence level with a 5% margin of error assuming a normal distribution.
    public UniformReservoir() {
        this();
    }

    
Creates a new UniformReservoir.

Parameters:
size the number of samples to keep in the sampling reservoir
    public UniformReservoir(int size) {
        this. = new AtomicLongArray(size);
        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