Skip to content

Instantly share code, notes, and snippets.

@Glamdring
Created July 14, 2017 13:52
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save Glamdring/06be638d3913c6a23ecf820852ede60b to your computer and use it in GitHub Desktop.
Save Glamdring/06be638d3913c6a23ecf820852ede60b to your computer and use it in GitHub Desktop.
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
Copy link

bdbogjoe commented Sep 19, 2018

should be :

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

@namsor
Copy link

namsor commented Oct 2, 2018

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

@Erkenbend
Copy link

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
Copy link

Is there a sample unit test to test that class?

@Glamdring
Copy link
Author

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