Created
July 14, 2017 13:52
-
-
Save Glamdring/06be638d3913c6a23ecf820852ede60b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Yes, @namsor is right: scheduleWithFixedDelay
or scheduleAtFixedRate
should be used, otherwise the command will just be executed once. Apart from that: great tutorial, thanks!
Is there a sample unit test to test that class?
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
Building on @dbbogjoe
Should be :
```
scheduler.scheduleWithFixedDelay(() -> {
semaphore.release(maxPermits - semaphore.availablePermits());
}, 0, 1, timePeriod);