Instantly share code, notes, and snippets.

Embed
What would you like to do?
public class SimpleRateLimiter {
private Semaphore semaphore;
private int maxPermits;
private TimeUnit timePeriod;
private ScheduledExecutorService scheduler;
public static SimpleRateLimiter create(int permits, TimeUnit timePeriod) {
SimpleRateLimiter limiter = new SimpleRateLimiter(permits, timePeriod);
limiter.schedulePermitReplenishment();
return limiter;
}
private SimpleRateLimiter(int permits, TimeUnit timePeriod) {
this.semaphore = new Semaphore(permits);
this.maxPermits = permits;
this.timePeriod = timePeriod;
}
public boolean tryAcquire() {
return semaphore.tryAcquire();
}
public void stop() {
scheduler.shutdownNow();
}
public void schedulePermitReplenishment() {
scheduler = Executors.newScheduledThreadPool(1);
scheduler.schedule(() -> {
semaphore.release(maxPermits - semaphore.availablePermits());
}, 1, timePeriod);
}
}
@bdbogjoe

This comment has been minimized.

Show comment
Hide comment
@bdbogjoe

bdbogjoe Sep 19, 2018

should be :

scheduler.schedule(() -> {
            semaphore.release(maxPermits - semaphore.availablePermits());
        }, 0, 1, timePeriod);`

bdbogjoe commented Sep 19, 2018

should be :

scheduler.schedule(() -> {
            semaphore.release(maxPermits - semaphore.availablePermits());
        }, 0, 1, timePeriod);`
@namsor

This comment has been minimized.

Show comment
Hide comment
@namsor

namsor Oct 2, 2018

Building on @dbbogjoe
Should be :
```
scheduler.scheduleWithFixedDelay(() -> {
semaphore.release(maxPermits - semaphore.availablePermits());
}, 0, 1, timePeriod);

namsor commented Oct 2, 2018

Building on @dbbogjoe
Should be :
```
scheduler.scheduleWithFixedDelay(() -> {
semaphore.release(maxPermits - semaphore.availablePermits());
}, 0, 1, timePeriod);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment