Created
September 14, 2015 02:32
-
-
Save si-yao/9d5da37a63487dc26ad1 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
package experience; | |
import java.util.Timer; | |
import java.util.TimerTask; | |
/** | |
* Count the API call in the last minute. | |
* Created by siyao on 9/13/15. | |
*/ | |
public class APICallCounter { | |
private static APICallCounter API_CALL_COUNTER; | |
private static final int PERIOD = 1000 * 10; // 10s | |
private static final int SLIDES = 10; | |
private int ptr; | |
private int count; | |
private int[] buffer; | |
private APICallCounter() { | |
int interval = PERIOD / SLIDES; | |
buffer = new int[SLIDES]; | |
ptr = 0; | |
count = 0; | |
TimerTask task = new TimerTask() { | |
@Override | |
public void run() { | |
int ptr2 = (ptr + 1) % SLIDES; | |
count -= buffer[ptr2]; | |
buffer[ptr2] = 0; | |
ptr = ptr2; | |
System.out.println("ptr->" + ptr); | |
} | |
}; | |
Timer timer = new Timer("timer"); | |
timer.scheduleAtFixedRate(task, interval, interval); | |
} | |
public static APICallCounter getInstance() { | |
if (API_CALL_COUNTER == null) { | |
return new APICallCounter(); | |
} else { | |
return API_CALL_COUNTER; | |
} | |
} | |
public int getCounting() { | |
return count; | |
} | |
public void increase(int k) { | |
buffer[ptr] += k; | |
count += k; | |
} | |
public static void main(String[] args) { | |
APICallCounter apiCallCounter = APICallCounter.getInstance(); | |
TimerTask timerTask = new TimerTask() { | |
@Override | |
public void run() { | |
apiCallCounter.increase(10); | |
System.out.println(apiCallCounter.getCounting()); | |
} | |
}; | |
Timer timer = new Timer("test"); | |
timer.scheduleAtFixedRate(timerTask, 0, 1000); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment