Last active
November 2, 2016 21:30
-
-
Save shikhar/bd8d51e51a02f0c93f1aafcf13f11ade 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 RateLimiter { | |
private final double permitsPerSecond; | |
private long nextAvailabilityNanos; | |
public RateLimiter(final double permitsPerSecond) { | |
this.permitsPerSecond = permitsPerSecond; | |
} | |
protected long nanoTime() { | |
return System.nanoTime(); | |
} | |
public long backoffNanos() { | |
return Math.max(0, nextAvailabilityNanos - nanoTime()); | |
} | |
public void take() { | |
take(1); | |
} | |
public void take(double permits) { | |
final long nowNanos = nanoTime(); | |
nextAvailabilityNanos = nowNanos | |
+ Math.max(0, nextAvailabilityNanos - nowNanos) | |
+ (long) (1000000000L * (permits / permitsPerSecond)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment