Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
 package com.robrua.orianna.type.api;
 
 import java.util.Timer;
Handles one rate limit

Author(s):
Rob Rua (FatalElement - NA) (robrua@alumni.cmu.edu)
public class SingleRateLimiter implements RateLimiter {
    
Resets the number of available permits
    private class ResetTask extends TimerTask {
        @Override
        public void run() {
            .drainPermits();
             = null;
            .release( - );
        }
    }
    private volatile int current;
    private final int limit;
    private final long millisPerEpoch;
    private volatile ResetTask resetter;
    private final Semaphore semaphore;
    private final Timer timer;

    

Parameters:
callsPerEpoch the number of calls allowed in each epoch
secondsPerEpoch the number of seconds in each epoch
    public SingleRateLimiter(final int callsPerEpochfinal int secondsPerEpoch) {
         = secondsPerEpoch * 1000L;
         = callsPerEpoch;
         = new Semaphore(true);
         = new Timer(true);
         = 0;
    }

    

Parameters:
limit the rate limit
    public SingleRateLimiter(final RateLimit limit) {
        this(limit.callsPerEpochlimit.secondsPerEpoch);
    }
    @Override
    public synchronized void registerCall() {
        if( == null) {
             = new ResetTask();
            .schedule();
        }
        --;
    }
    @Override
    public synchronized void resetIn(final long millis) {
        if( != null) {
            .cancel();
        }
         = new ResetTask();
        .drainPermits();
        .schedule(millis);
    }
    @Override
    public void waitForCall() {
        ++;
    }
New to GrepCode? Check out our FAQ X