Skip to content

Instantly share code, notes, and snippets.

@nowucca
Created June 8, 2015 18:20
Show Gist options
  • Save nowucca/7fbd490916b4c8bdef54 to your computer and use it in GitHub Desktop.
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
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