Created
June 8, 2015 18:20
-
-
Save nowucca/7fbd490916b4c8bdef54 to your computer and use it in GitHub Desktop.
Throttle a particular action if it happens too often within a period of time
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
package com.nowucca.util; | |
import com.nowucca.exception.InternalException; | |
import java.util.concurrent.atomic.AtomicInteger; | |
/** | |
*/ | |
public class Throttle { | |
private static int threshold; | |
private long beginningOfWindow; | |
private long windowSizeMillis; | |
private AtomicInteger count; | |
public Throttle(int threshold, long windowSizeMillis) { | |
assert windowSizeMillis > 0; | |
assert threshold > 0; | |
this.threshold = threshold; | |
this.windowSizeMillis = windowSizeMillis; | |
this.count = new AtomicInteger(0); | |
} | |
public void throttle() throws ThrottledException, InternalException { | |
long now = System.currentTimeMillis(); | |
if (now - beginningOfWindow > windowSizeMillis) { | |
count.set(0); | |
beginningOfWindow = now; | |
} | |
if (count.incrementAndGet() > threshold) { | |
throw new ThrottledException(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment