Skip to content

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.

Copy link

@bdbogjoe bdbogjoe commented Sep 19, 2018

should be :

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

This comment has been minimized.

Copy link

@namsor namsor commented Oct 2, 2018

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

@Erkenbend

This comment has been minimized.

Copy link

@Erkenbend Erkenbend commented Jan 7, 2019

Yes, @namsor is right: scheduleWithFixedDelay or scheduleAtFixedRate should be used, otherwise the command will just be executed once. Apart from that: great tutorial, thanks!

@ajdelr645

This comment has been minimized.

Copy link

@ajdelr645 ajdelr645 commented Mar 24, 2020

Is there a sample unit test to test that class?

@Glamdring

This comment has been minimized.

Copy link
Owner Author

@Glamdring Glamdring commented Mar 25, 2020

I don't have one easily available

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