Created
January 18, 2017 15:30
-
-
Save deyindra/521cff34cca7f7779d3587219c548693 to your computer and use it in GitHub Desktop.
RateLimiter
This file contains hidden or 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 long minTime; | |
//holds time of last action (past or future!) | |
private volatile long lastSchedAction; | |
private volatile boolean forFirstTime; | |
public RateLimiter(float maxRate, long duration, TimeUnit unit) { | |
if(maxRate <= 0.0f) { | |
throw new IllegalArgumentException("Invalid rate"); | |
} | |
if(unit.compareTo(TimeUnit.MILLISECONDS)<0){ | |
throw new IllegalArgumentException("Invalid time unit"); | |
} | |
this.forFirstTime = true; | |
this.minTime = (long)(unit.toMillis(duration) / maxRate); | |
} | |
public void consume() throws InterruptedException { | |
if(forFirstTime){ | |
synchronized (this){ | |
forFirstTime = false; | |
lastSchedAction = System.currentTimeMillis(); | |
} | |
}else{ | |
long curTime = System.currentTimeMillis(); | |
long timeLeft; | |
synchronized (this) { | |
timeLeft = lastSchedAction + minTime - curTime; | |
if (timeLeft > 0) { | |
lastSchedAction += minTime; | |
} else { | |
lastSchedAction = curTime; | |
} | |
} | |
if(timeLeft > 0) { | |
Thread.sleep(timeLeft); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment